HTML Tutorial | HTML5 API | Web Storage

Web Storage API

The Web Storage API allows the web browser to store data directly in order to overcome the limitations of traditional cookies.

Before HTML5, whenever an application requested data from the server, that information was stored in cookies.
Web Storage, however, allows a larger amount of information to be stored safely on the user side.
Web Storage provides at least 5 MB of space, and this information is never sent to the server.

This Web Storage exists only once per origin.
An origin is an identifier made up of a domain and a protocol pair.
Therefore, all web pages belonging to the same origin store the same data and can access the same data.

The major web browser versions that support the Web Storage API are as follows.

API ie chrome firefox safari opera
Web Storage 8.0 4.0 3.5 4.0 11.5

Checking Web Storage Support

Before using Web Storage, first check whether the user’s web browser supports it.

Syntax

if (typeof(Storage) !== "undefined") {
    // Code for web storage
} else {
    // Message for browsers that do not support web storage
}

Web Storage Objects

The Web Storage API provides two objects that allow users to store data.

  • sessionStorage object: An object that stores data for only one session.
  • localStorage object: An object that can store data without an expiration period.

sessionStorage Object

The sessionStorage object stores data for only one session.
Therefore, when the user closes the browser tab or window, the data stored in this object disappears.

Example

function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (sessionStorage.clickcount) { 
            sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1; 
        } else { 
            sessionStorage.clickcount = 1; 
        }
        document.getElementById("counter").innerHTML = "The current counter value is " + sessionStorage.clickcount + ".";
    }
}

localStorage Object

The localStorage object stores data without an expiration period. Therefore, stored data does not disappear even if the browser tab or window is closed or the computer is rebooted.

Example

function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) { 
            localStorage.clickcount = Number(localStorage.clickcount) + 1; 
        } else { 
            localStorage.clickcount = 1; 
        }
        document.getElementById("counter").innerHTML = "The current counter value is " + localStorage.clickcount + ".";
    }
}