Before HTML5, application data of web applications are stored in cookies. In this article I will explain you what is Local Storage and Session Storage Object, How we can use it our application, What is the difference between Local and Session Storage object. Why HTML Local Storage better than cookies. So lets start with What .
What is Local Storage?
Note: Key/Value pairs are always stored as strings. Remember to convert them to another format when needed!
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
- window.localStorage – stores data with no expiration date
// How to store data localStorage.setItem("Key", "Value"); // How to retrieve document.getElementById("divId").innerHTML = localStorage.getItem("Key");
What is Session Storage Object?
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
- window.sessionStorage – stores data for one session (data is lost when the browser tab is closed)
// How to store data sesionStorage.setItem("Key", "Value"); // How to retrieve document.getElementById("divId").innerHTML = sessionStorage.getItem("Key");
Why HTML Local Storage better than cookies?
- Cookies are included with every HTTP request, thereby slowing down your web application by needlessly transmitting the same data over and over
- Cookies are included with every HTTP request, thereby sending data unencrypted over the internet (unless your entire web application is served over SSL)
- Cookies are limited to about 4 KB of data — enough to slow down your application (see above), but not enough to be terribly useful.
- Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.