Use localStorage and sessionStorage

javascript

As an alternative to cookies, you can use localStorage to store information on the client side. Unlike cookies, however, this data won't be sent to the server.

localStorage along with sessionStorage is cross-browser. The difference being that localStorage is indefinitely persistent.

// in case you'd like to check if it is supported if (typeof(Storage) === "undefined") {} // use a fallback // setting value pair localStorage.setItem('key', 'value') // retrieving value localStorage.getItem('key') // "getItem" will either return a string or null // this means you have to parse the values var number = localStorage.getItem('number') * 1 var boolean = localStorage.getItem('boolean') == 'true' localStorage.setItem('key2', JSON.stringify( {'json': 'data'} )) var json = JSON.parse( localStorage.getItem('key2') )

Keep in mind that by using JSON.stringify() prototype and private information will be lost.

Alternatively to getItem and setItem you can use a dots to access. Similar to innerHTML.

localStorage.key = 'value' var value = localStorage.key

Reference

No known

History May 02, 2017