shivank.arya

January 2012 Previous month Next month

HTML 5 Web Storage

CACHING application data is fundamental in nearly all applications, web or desktop.

Up until now, storing data in a web application required you either to store it on the server side and create some linking key between the client and the server—or it would be stored in cookies. The first approach has an unnecessary and undesirable performance impact. And cookies just suck when it comes to caching because they are overly complicated to use and their lifecycle has to be handled with workarounds. 

 

Please welcome HTML-5 web storage mechanisms to the rescue - sessionStorage and localStorage. Web Storage—supported in all the latest browsers. 

SessionStorage

Data cached using sessionstorage has a lifetime of a session. This means that it is available only for the current open window till it is closed. If you opened another window on the same domain, it wouldn’t have access to that session data. This is useful to keep a shopping session within one window, whereas cookies would let the session "leak" from one window to another.

LocalStorage

It is based around the domain and spans all windows that are open on that domain. If you set some data on local storage it immediately becomes available on any other window on the same domain, but also remains available until it is explicitly deleted either by you as the web author or by the user. Otherwise, you can close your browser, reboot your machine, come back to it days later, and the data will still be there. Persistent data without the hassle of cookies: having to reset the expiry again and again.

Code Examples for SessionStorage -

Setting data
Strings - window.sessionStorage.setItem("name", "Shivank Arya");
Objects - window.sessionStorage.setItem("graphs", JSON.stringify(allGraphs));

Note - Browsers convert objects to string before caching. So, if we try to directly save the object, it will actually save "[Object object]" 
Accessing data
Strings - window.sessionStorage.getItem("name");
Objects - JSON.parse(window.sessionStorage.getItem("graphs"));
Removing data
window.sessionStorage.removeItem("name");
window.sessionStorage.clear();
Checking if your browser supports web storage
if(window.sessionStorage){
    data = window.sessionStorage.getItem(path);}

Note: LocalStorage has similar APIs for managing web storage.

 

Good luck.

Actions