Caching with HTML5 localStorage and sessionStorage
In this recipe, we will learn how to use the HTML5 Storage API (it's also called Web Storage, or DOM Storage) with localStorage
and sessionStorage
objects, in order to store non-sensitive data on the client.
Getting ready
First, we create an empty project with VS 2017, and use JavaScript code to store data.
We need as a minimum browser requirement IE8, Firefox 3.5, or Chrome 4.0 to benefit from HTML5 capabilities in the browser.
All the following methods and properties are available for both localStorage
and seesionStorage
:
getItem(key)
: Store a key/value pairsetItem(key, value)
: Return a value associated with a keyremoveItem(key)
: Delete a key/value pair with a keyclear()
: Delete all key/value pairslength
: Return the number of stored pairs
How to do it...
- To test if
localStorage
orsessionStorage
is available on our browser, we can use the following code:
(function() { if (typeof sessionStorage != 'undefined') // or if (window['localStorage...