DEV Community

Cover image for HTML5 web storage – offline storage solution for the web
Mandar Badve
Mandar Badve

Posted on • Updated on • Originally published at blog.mandarbadve.com

HTML5 web storage – offline storage solution for the web

This was originally posted on my blog

Using HTML5 you can store data into user’s browser. Before HTML5, there was only one way to store data using cookies. This web storage stores data in key/value pair. You can use this technique to store data offline.

How to check that browser supports web storage?

    if(typeof(Storage) !== "undefined")
    {
        // Browser supports web storage. So you can use local and session storage
    }
    else
    {
        // Browser does not support web storage.
    }
Enter fullscreen mode Exit fullscreen mode

There are two types of the web storage

  1. Local Storage
  2. Session Storage

Local Storage

You can store data into local storage like

localStorage.key = "value";
Enter fullscreen mode Exit fullscreen mode

And you can retrieve it as

var localStorageValue = localStorage.key;
Enter fullscreen mode Exit fullscreen mode

This storage is persisted even you closes and reopen the browser.

Session Storage

This storage is same as the local storage. One thing differs from local storage is that, the data will be lost if user closes the browser. So if you want to store data per session, go with this storage.

You can store data as follows

sessionStorage.key = "value";
Enter fullscreen mode Exit fullscreen mode

After you can retrieve as

var sessionStorageValue = sessionStorage.key;
Enter fullscreen mode Exit fullscreen mode

How to check/debug web storage is working or not?

Developer tools of the browser will show data stored into the web storage. Following image taken from w3schools.com describes the where you can find the web storage.

HTML5 web storage – offline storage solution for the web

You can check your browser supports how many HTML5 features just opening http://html5test.com/ into your browser.

Discussion (0)