Local Storage And Session Storage

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

  1. localStorage.setItem('ProductName''Mobile');   

Local strorage stores the data in key/value format. Same syntax can be written, as shown below.

  1. 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 

  1. var ProductName = localStorage.getItem('ProductName');  
  2.   
  3. //OR  
  4.   
  5. 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

  1. localStorage.removeItem('ProductName');   

This will remove ‘ProductName’ from local storage under current domain.

  1. localStorage.clear();   

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 

  1. sessionStorage.setItem('ProductName''Mobile');  
  2.   
  3. //OR  
  4.   
  5. sessionStorage.ProductName = 'Mobile';   

Get session storage 

  1. var ProductName = sessionStorage.getItem('ProductName');  
  2.   
  3. //OR  
  4.   
  5. var ProductName = sessionStorage.ProductName;   

Remove session storage 

  1. sessionStorage.removeItem('ProductName');  
  2. 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.