What is localStorage?
local storage is property for accessing Storage object, which is used to store and retrieve data from user’s browser. It is accessible only at client side not at server side like cookie.
Data stored in localStorage is accessible thought all pages under same domain, until user does not delete it manually. Even though user closes the browser, data will be accessible next time.
Set local storage: localStorage.setItem('ProductName', 'Mobile');
localStrorage stores data in Key/Value format. Same syntax can be written as
localStorage.ProductName = 'Mobile';
Note: Here ProductName is key and Mobile is value for local storage. Key is case sensitive so here ProductName and productname will be considered as two different keys.
Get local storage:
var ProductName = localStorage.getItem('ProductName');
var ProductName = localStorage.ProductName;
localStorage will always return value in string. So if required, then one need to cast the value in needed type.
Remove local storage:
This will remove ‘ProductName’ from local storage of under current domain.
This will remove all the local storage for current domain.
What is sessionStorage?
Session storage is almost same as local storage. Only difference is, session storage will get cleared once user will close the browser window.
All the example written for localStorage can be used for sessionStorage as below
Set session storage:
sessionStorage.ProductName = 'Mobile';
Get session storage:
var ProductName = sessionStorage.getItem('ProductName');
var ProductName = sessionStorage.ProductName;
Remove session storage:
Browser Support for Local Storage and Session Storage:
Storage capacity for localStorage and sessionStorage is vary based on browser. Generally browsers provides around 5MB of storage space.