Monday 4 November 2019

javascript - How to get JS variable to retain value after page refresh?




Is it possible to permanently change a javascript variable? As in, if I set the variable X and make that equal to 1. Then onClick of a button change that variable to 2. How can I get that variable to stay at 2 on refresh of the page?


Answer



This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it.




When you need to set a variable that should be reflected in the next page(s), use:



var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);


And in any page (like when the page has loaded), get it like:



var someVarName = localStorage.getItem("someVarKey");



.getItem() will return null if no value stored, or the value stored.



Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify and JSON.parse. Technically, whenever you call .setItem(), it will call .toString() on the value and store that.



MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage isn't available.



It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).







References:




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...