Introduction
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.
- 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.
- 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.
Figure: Session Storage
Figure: Local Storage
The following functions are used to access local storage in JavaScript:
- To store data in the 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 the 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 the object as in the following:
- var object=JSON.parse(localStorage.getItem(‘object’));
-
To delete a 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 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.
Summary
In this article, we learned about HTML5 Web Storage - Part 2 (Local Storage).