Persistent storage describes a mechanism that preserves the value of data over the lifetime of an executed script or program.
Persistent Storage in JavaScript
The persistent storage or "Web Storage" mechanism has been introduced with the draft of the HTML5 standard. JavaScript provides two different objects for this purpose:
sessionStorage
The values saved to the sessionStorage object are valid for the length of a browsing session. They are only accessible from the browser (or tab) that initially stored the data. Access is not limited to pages of the same domain.
localStorage
The values saved to the localStorage object are valid until explicitly removed via JavaScript. The localStorage object is unique to each domain.
Usage
A Web Storage object can only save strings. If it is required to save non-string data, the best approach is to use the JSON.stringify()
function.
The two most important functions are getItem
and setItem
.
In order to write a value to the session storage, the following action has to be taken:
sessionStorage.setItem("myKey", "myValue");
To read the just-saved value, the following action is required:
sessionStorage.getItem("test");
Further objects and methods provided by the Web Storage are described here:
- https://davidwalsh.name/html5-storage
- https://html.spec.whatwg.org/multipage/webstorage.html
- https://code.google.com/p/sessionstorage/
Compatibility
Most modern browsers support Web Storage nowadays.
A fallback solution that is able to use Cookies if no Web Storage is available is Lawnchair
Persistent Storage in other languages
Languages like Android-Java, Python or VBA also provide mechanisms to preserve the values of certain variables over the lifetime of the program.