Modern browsers come with the capability to store data locally in the browser storage. The dat acan be stored in a key value pair. Think of it as the counterpart of database on server side. A typical way of storing the data in local storage is
if(typeof(Storage) !== "undefined") {
localStorage.setItem("name","Ekagra");
} else {
console.log("No local storage available");
}
Retrieving the data is equally easy
if(typeof(Storage) !== "undefined") {
var name = localStorage.getItem("name");
} else {
console.log("No local storage available");
}
The data can also be retrieved using the following syntax
var name = localStorage.name;
To remove the item
localStorage.removeItem("name");
All modern browsers support local storage. Local storage is available on per domain basis in the browser and has a limit of 5 MB. So be careful about storing large amount of data. The data can also be stored on per session basis. That is handled by sessionStorage. The code for sessionStorage looks pretty similar
Add
sessionStorage.setItem("name","Ekagra");
Fetch
var name = sessionStorage.getItem("name");
Remove
sessionStorage.removeItem("name");
If same application is opened in two instance of browser than they share the same localStorage but has different sessionStorage.
Local storage can be used to replace cookies. Normally if we have to share some data to be available on client site between pages, the data is persisted as cookies. However with cookies the payload increases as all the cookies are embedded in every request response. Using local storage results in data remaining on the client side only. The data is also remembered till the user chooses to clean it. That means if the user accesses the application after a period, the local storage data would still be available.
To clear the complete storage use
localStorage.clear();
To clear the complete storage use
localStorage.clear();
No comments:
Post a Comment