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.
- 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.
- 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.
Figure: Session Storage
Figure: Local Storage
The following functions are used to access local storage in JavaScript:
- To store data in local storage setItem() function is used.
- localStorage.setItem (‘key’,’value’);
Example:
- 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:
- localStorage.setItem (‘object’, JSON.stringify(object));
- To retrieve data from local storage getItem() function is used.
- localStorage.getItem(‘key’);
Example:
- var username= localStorage.getItem(‘username’);
If JSON string is stored in local storage, then you can convert it into object as in the following:
- var object=JSON.parse(localStorage.getItem(‘object’));
- To delete particular key from local storage removeItem function is used.
- localStorage.removeItem(‘key’);
Example:
- localStorage.removeItem(‘username’);
- To delete all keys from local storage clear function is used:
To get all KEY / VALUE pairs from local storage, you can loop through local storage like the following:
- for(var i=0;i< localStorage.length;i++)
- {
- var key= localStorage.key(i);
- var value= localStorage.getItem(key);
- }
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.