This site is mobile accessible. Press the "Tap Here" button to use a smaller font-size.
Smartphone icons created by Freepik - Flaticon
HTML web storage; better than cookies.
The numbers in the table specify the first browser version that fully supports Web Storage.
API | |||||
---|---|---|---|---|---|
Web Storage | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
HTML web storage provides two objects for storing data on the client:
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") { // Code for localStorage/sessionStorage. } else { // Sorry! No Web Storage support.. }
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.
// Store localStorage.setItem("lastname", "Smith"); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname");
The example above could also be written like this:
// Store localStorage.lastname = "Smith"; // Retrieve document.getElementById("result").innerHTML = localStorage.lastname;
The syntax for removing the "lastname" localStorage item is as follows:
localStorage.removeItem("lastname");
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!
The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase 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
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.The following example 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.";