How to create local storage effect with HTML5

Another useful API with HTML5 is the ‘local storage’ API. The local storage is intended to be used a multiple window or large amount of data storage capacity on user’s local (PC) machine. 

Web applications in this way are able to use a local machine as a cookie / session storage on ‘steroids’, figuratively speaking. The local storage enables storage of large amount of data spanning throughout multiple browsing session, for instance entire user created documents, and similar.

Although old fashion cookies may handle larger amount of data, they have a big problem that is they are being sent out with every HTTP request (page call). To improve that and allow developers to utilize better client devices (browser’s cache), HTML5 introduced two pre-defined object, localStorage and sessionStorage.

HTML5 local storage API, thus, describes these two objects:

  • localStorage – this object will store data with no expiration date.
  • sessionStorage – this object will allow us to store data for one session; session is not closed if a TAB is closed, but only if the browser gets closed.

Example on how to assign and retrieve local storage data:

// store

localStorage.itemname = “my local PC”;

sessionStorage.itemsession = “July 11”;

// retrieve

document.getElementByTagname(body[0]).innerHTML = localStorage.itemname;

document.getElementById(“para”).innerHTML = sessionStorage.itemsession;

In the example above, the local PC will ‘remember’ the ‘itemname’ permanently, while ‘itemsession’ only for one session. 

As the local storage does not drop data after time, it is useful to know how to manually remove them. Removing data from ‘localStorage’ cache is done with the method removeItem, such as shown here:

localStorage.removeItem(“itemname”);

Example