HTML5 Web Storage - Part 2 (Local Storage)

In this article we learn about the second type of Web Storage, local storage and difference between session storage and 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 second type of HTML Web Storage. Like session storage it also stores data in KEY / VALUE pair of strings. The following points gives the comparison of session storage and local storage.

  1. Session storage stores the data for only current session of browser, when browser closes data in session storage is cleared. On the other hand, the data stored in local storage is not deleted automatically when 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 current window of browser. But the data in the local storage can be shared between multiple windows of 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 local storage setItem() function is used.
    1. localStorage.setItem (‘key’,’value’);  
    Example:
    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 local storage getItem() function is used.
    1. localStorage.getItem(‘key’);  
    Example:
    1. var username= localStorage.getItem(‘username’);  
    If JSON string is stored in local storage, then you can convert it into object as in the following:
    1. var object=JSON.parse(localStorage.getItem(‘object’));  
  3. To delete particular key from local storage removeItem function is used.
    1. localStorage.removeItem(‘key’);  
    Example:
    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 key= localStorage.key(i);  
    4.    var value= localStorage.getItem(key);  
    5. }  

Note: Session storage and local storage saves data in unencrypted string in 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.