Web storage enables web applications to store data locally in the user’s browser.
Before HTML5, application data was typically stored in cookies, which were sent with every server request. Web storage offers improved security and performance, allowing larger amounts of data (at least 5MB) to be stored locally without impacting website performance.
Unlike cookies, data stored in web storage is not transferred to the server, and each origin (domain and protocol) can store and access the same data across all pages.
The numbers in the table indicate the earliest browser version that fully supports Web Storage.
HTML web storage offers two objects for client-side data storage:
Prior to utilizing web storage, verify browser support for localStorage and sessionStorage.
if (typeof(Storage) !== “undefined”) { // Code for localStorage/sessionStorage. } else { // Sorry! No Web Storage support.. |
The localStorage object stores data indefinitely without an expiration date. Data persists even after the browser is closed and remains accessible in the future, whether it’s the next day, week, or year.
// Store localStorage.setItem(“lastname”, “Smith”); // Retrieve document.getElementById(“result”).innerHTML = localStorage.getItem(“lastname”); |
Here’s the example explained:
The example above can alternatively be written as:
// Store localStorage.lastname = “Smith”; // Retrieve document.getElementById(“result”).innerHTML = localStorage.lastname; |
Here’s the syntax for removing the “lastname” localStorage item:
localStorage.removeItem(“lastname”); |
Note: Name/value pairs in localStorage are always stored as strings. Remember to convert them to another format when necessary!
The following example demonstrates counting the number of times a user has clicked a button. In this code, the string value is converted to a number to increment the counter:
if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount) + 1; } else { localStorage.clickcount = 1; } document.getElementById(“result”).innerHTML = “You have clicked the button “ + localStorage.clickcount + ” time(s).”; |
The sessionStorage object functions similarly to the localStorage object, but it stores data only for the duration of one session. Data stored in sessionStorage is deleted when the user closes the specific browser tab.
Here’s an example that counts the number of times a user has clicked a button in the current session:
if (sessionStorage.clickcount) { sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1; } else { sessionStorage.clickcount = 1; } document.getElementById(“result”).innerHTML = “You have clicked the button “ + sessionStorage.clickcount + ” time(s) in this session.”; |