HTML5 Web Storage - Part 2 (Local Storage)


In the previous article "HTML5 Web Storage Part 1- Local Storage" we learned about HTML Web Storage and session storage. In this article, we will learn about the second type of Web Storage, local storage and difference between session storage and local storage.

Local Storage

Local Storage is the second type of HTML Web Storage. Like session storage, it also stores data in the KEY / VALUE pair of strings. The following points give the comparison of session storage and local storage.
  1. Session storage stores the data for only the current session of the browser when the browser closes data in session storage is cleared. On the other hand, the data stored in local storage is not deleted automatically when the current browser window closed. Data in local storage is cleared only when it is manually deleted.
  2. The data in session storage are accessible only in the current window of the browser. But the data in the local storage can be shared between multiple windows of the browser.
    Session Storage
    Figure: Session Storage
    Local Storage
    Figure: Local Storage
The following functions are used to access local storage in JavaScript:
  1. To store data in the local storage setItem() function is used.
    1. localStorage.setItem (‘key’,’value’);    
    1. localStorage.setItem (‘username’,’ABC’);    
    We can only store strings in local storage. To save objects in local first convert object into JSON string and then store this string in local storage as in the following:
    1. localStorage.setItem (‘object’, JSON.stringify(object));    
  2. To retrieve data from the local storage getItem() function is used.
    1. localStorage.getItem(‘key’);    
    1. var usernamelocalStorage.getItem(‘username’);     
    If JSON string is stored in local storage, then you can convert it into the object as in the following:
    1. var object=JSON.parse(localStorage.getItem(‘object’));    
  3. To delete a particular key from local storage removeItem function is used.
    1. localStorage.removeItem(‘key’);     
    1. localStorage.removeItem(‘username’);    
  4.  To delete all keys from local storage clear function is used:
    1. localStorage.clear();    
    To get all KEY / VALUE pairs from local storage, you can loop through local storage like the following:
    1. for(var i=0;i< localStorage.length;i++)    
    2. {    
    3.    var keylocalStorage.key(i);    
    4.    var valuelocalStorage.getItem(key);    
    5. }    
Session storage and local storage saves data in unencrypted string in the regular browser cache. It is not secure storage, so it should not be used to save sensitive user data like security numbers, credit card numbers, etc.


In this article, we learned about HTML5 Web Storage - Part 2 (Local Storage).