There are times, we want to store something in a page session.

Lifespan of a page session is lasted until they (either window or tab) are closed. It lasts, even though page is refreshed. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

// Save data to sessionStorage
window.sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = window.sessionStorage.getItem('key');

// Remove saved data from sessionStorage
window.sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
window.sessionStorage.clear();

The above example, store a value in string type into sessionStorage, and its’ key is key. The value can be retrieve later with calling getItem() of sessionStorage.

var o = window.JSON.stringify({key:"value"});

window.sessionStorage.setItem("object", o);

var a = window.JSON.parse(window.sessionStorage.getItem("object"));

By default, the stored value is a string type. Thus, to store an object, use JSON.stringify() to convert JavaScript value to a JSON string before setting it into an item. Use JSON.parse() to retrieve and restore the item into a JavaScript value.

References

Window.sessionStorage
JSON

Last modified: May 23, 2018

Author