HTML5 Local Storage using Web Storage API

Before HTML5, application data had to be stored in cookies. Cookies can be used for persistent local storage of small amounts of data and they have the following drawbacks.

  • 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, but not enough to be terribly useful

With HTML5 Local Storage, web applications can store data locally within the user's browser. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Storage API can store key/value pairs, in a much more intuitive fashion than using cookies. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML Local Storage Objects

HTML local storage provides two objects for storing data on the client:

window.sessionStorage - maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, 
including page reloads and restores)
window.localStorage - does the same thing, but persists even when the browser is closed and reopened.

Invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved and removed.

Web Storage interfaces

Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage — which provide access to the current domain's 
session and local Storage objects respectively.
The storage event is fired on a Document's Window object when a storage area changes.

Before using local storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! Your browser doesn't support local storage..

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.

The following example creates a localStorage name/value pair with name="lastname" and value="gopi" and
retrieve the value of "lastname" and insert it into the element with id="result"

// Store
localStorage.setItem("lastname", "gopi");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Note: Calling setItem() with a named key that already exists will silently overwrite the previous value. Calling getItem() with a non-existent key will return null rather than throw an exception.

The example above could also be written like as:
// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
Following are the methods for removing the value for a given named key, and clearing the entire storage area
Note: Calling removeItem() with a non-existent key will do nothing.

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 sessionStorage 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. 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.";

Tracking Changes To The HTML5 STORAGE Area

If you want to keep track programmatically of when the storage area changes, you can trap the storage event. The storage event is fired on the window object whenever setItem(), removeItem(), or clear() is called and actually changes something. For example, if you set an item to its existing value or call clear() when there are no named keys, the storage event will not fire, because nothing actually changed in the storage area.

The storage event is supported everywhere the localStorage object is supported, which includes Internet Explorer 8. But IE 8 does not support the W3C standard addEventListener. Therefore, to hook the storage event, you’ll need to check which event mechanism the browser supports.
if (window.addEventListener) {
  window.addEventListener("storage", handle_storage, false);
} else {
  window.attachEvent("onstorage", handle_storage);
The handle_storage callback function will be called with a StorageEvent object, except in Internet Explorer where the event object is stored in window.event.
function handle_storage(e) {
  if (!e) { e = window.event; }
the variable e will be a StorageEvent object, which has the following useful properties


Property Type Description
key string he named key that was added, removed, or modified
oldValue any the previous value (now overwritten), or null if a new item was added
newValue any the new value, or null if an item was removed
url* string the page which called a method that triggered this change
*the url property was originally called uri. Some browser version follow uri instead of url. So you should check whether the url property exists, and if not, check for the uri property instead.

Note: The storage event is not cancelable. From within the handle_storage callback function, there is no way to stop the change from occurring. It’s simply a way for the browser to tell you, "Just Something happend".
“QUOTA_EXCEEDED_ERR” is the exception that will get thrown if you exceed your storage quota of 5 megabytes.

Browser Support

Following are the browser versions which supports Web Storage API
You can check here for other browsers.


    Blogger Comment
    Facebook Comment


Post a Comment