When you refresh a page, all stored values are lost thought its possible to retain the variable value.This is possible with window.localStorage
(or window.sessionStorage
). The difference is explained at MDN's DOM storage guide (linked below).
When you need to set a variable that should be reflected in the next page(s), use:
var someVarName = "value";
localStorage.setItem("someVarName", someVarName);
And in any page (like when the page has loaded), get it like:
var someVarName = localStorage.getItem("someVarName");
.getItem()
will return null 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.).