Set Data Locally Using Local And Session Storage in HTML5

Posted By : Panaru Chaudhary | 17-Apr-2017

A website can store data up to 10MB size in the browser in `Local’ or `Session Storage’ with help of HTML5.

By using Local/Session Storage, we can store up to 10MB data in browser’s memory. Almost all modern browsers supports local/session storage. Difference between Local Storage and Session storage is on closing browser/tab, Session Storage will be removed whereas  Local Storage data will remain in the browser until the user physically deletes it or removes the same using removeItem option.

How to Set data into Local Storage:

<script>

   if(window.localStorage){

       try{

           window.localStorage.setItem(key, data );

       }catch(e){

           return false;
}
}
OR
var key = 'list-of-university'
var data = '[{"1":"JNU"},{"2":"DU"},{"3":"BHU"}]';
   if(window.localStorage){
       try{
           window.localStorage.setItem(key, data );
       }catch(e){
           return false;
       }
     }
    </scirpt> 

How to Set data into Session Storage :  

 

<script>

  if(window.sessionStorage){        try{            window.sessionStorage.setItem(key, data );        }catch(e){            return false;        }     } <script>

sessionStorage property allows you to access a session Storage object for the current origin.sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

 

Delete or Remove Data from Local  And Session Storage :

After setting and getting data from browser, if you feel that the data is useful any longer and decide to delete, then you can remove the same using localStorage.removeItem(key)

<script>    if(window.localStorage){        try{            window.localStorage.removeItem(key);        }catch(e){            return false;        }    }         if(window.sessionStorage){        try{            window.sessionStorage.removeItem(key);        }catch(e){            return false;        }    } </scirpt>

 

 

About Author

Author Image
Panaru Chaudhary

Panaru is a bright Java developer with good knowledge in Core java , advance Java, Spring , Hibernate and jQuery.

Request for Proposal

Name is required

Comment is required

Sending message..