What is local storage?
Local storage is a property for accessing a storage object, which is used to store and retrieve the data from the user’s Browser. It is accessible only at client side and not at Server side like a cookie.
The data stored in local storage is accessible. All the pages are under the same domain, unless the user does not delete it manually. Even though the user closes the Bowser, the data will be accessible next time.
Set local storage
- localStorage.setItem('ProductName', 'Mobile');
Local strorage stores the data in key/value format. Same syntax can be written, as shown below.
- localStorage.ProductName = 'Mobile';
Note
Here, ProductName is the key and Mobile is the 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;
Local storage will always return value in the string if required, then one needs to cast the value in the needed type.
Remove local storage
- localStorage.removeItem('ProductName');
This will remove ‘ProductName’ from local storage under current domain.
This will remove all the local storage for the current domain.
What is session storage?
Session storage is almost the same as local storage. The only difference is, session storage will be cleared, once the user closes the Browser Window.
Syntax
All the examples written for local storage can be used for session storage, as shown below.
Set session storage
- sessionStorage.setItem('ProductName', 'Mobile');
-
-
-
- sessionStorage.ProductName = 'Mobile';
Get session storage
- var ProductName = sessionStorage.getItem('ProductName');
-
-
-
- var ProductName = sessionStorage.ProductName;
Remove session storage
- sessionStorage.removeItem('ProductName');
- sessionStorage.clear();
The Browser support for local storage and session storage is shown below.
Browser | Minimum Version |
Chrome | 4.0 |
Firefox | 3.5 |
Internet Explorer | 8.0 |
Opera | 10.50 |
Safari | 4.0 |
Storage capacity
Storage capacity for local storage and session storage varies based on the Browser. Generally, the Browsers provide around 5MB of storage space.