javascript

Local Storage and Session Storage

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.

Syntax:

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');

OR

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:

localStorage.removeItem('ProductName');

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

localStorage.clear();

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.

Syntax:

All the example written for localStorage can be used for sessionStorage as below

Set session storage:

sessionStorage.setItem('ProductName', 'Mobile');

OR

sessionStorage.ProductName = 'Mobile';

Get session storage:

var ProductName = sessionStorage.getItem('ProductName');

OR

var ProductName = sessionStorage.ProductName;

Remove session storage:

sessionStorage.removeItem('ProductName');

sessionStorage.clear();

Browser Support for Local Storage and Session Storage:

Browser Version
Chrome 4.0
Firefox 3.5
Internet Explorer 8.0
Opera 10.50
Safari 4.0

Storage Capacity:

Storage capacity for localStorage and sessionStorage is vary based on browser. Generally browsers provides around 5MB of storage space.

3 Replies to “Local Storage and Session Storage”

Leave a Reply