Local Storage and Session Storage
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?
One of the major drawback of cookies where local storage comes into the picture is that cookies included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data. Data stored in Local Storage i.e in (local storage and session object) is a Key/Value pair. You store data based on a named key, then you can retrieve that data with the same key. The named key is a string. The data can be any type supported by JavaScript, including strings, Boolean, integers, or floats. However, the data is actually stored as a string.
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");
IE | FIREFOX | SAFARI | CHROME | OPERA | IPHONE | ANDROID |
---|---|---|---|---|---|---|
8.0+ | 3.5+ | 4.0+ | 4.0+ | 10.5+ | 2.0+ | 2.0+ |
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.