#31 HTML Web Storage API

HTML web storage api is a mechanism to store data locally within the user’s browser.

Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML Web Storage Objects

Web storage provides two types of global web storage objects

  • window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
  • window.localStorage - stores data with no expiration date

session storage

The sessionStorage 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:

See the Pen session storage by Arpit (@soniarpit) on CodePen.

We create the simple button. In a session, user can click the button for any number of times he/she wants.

The sessionStorage.clickcount given the number of times particular button clicked.

This count is then displayed on the web browser.

If you closed the browser tag then this count again set to 1

local storage

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.

See the Pen local storage by Arpit (@soniarpit) on CodePen.

Create a localStorage name/value pair with name="blogname" and value="CodeSnail"

Retrieve the value of "blogname" and insert it into the element with id=“result”

The example above could also be written like this:

// Store
localStorage.blogname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.blogname;

The syntax for removing the “lastname” localStorage item is as follows:

localStorage.removeItem("blogname");

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

See the Pen local storage click count by Arpit (@soniarpit) on CodePen.

Previous: #30 HTML Drag and Drop API

Next: #32 Difference between HTML and XHTML