Gil Fink's Blog

January 11, 2011

Using Web Storage in Web Applications

Web Storage is a specification that was a part of HTML5 but was moved to its own specification. Currently, it is only a W3C editor draft but it is implemented in all the major browsers (even in IE from IE8) by the name Local Storage or DOM Storage. In this post I’m going to explain what is Web Storage and how you can use it even today in your web application/site.

Before Web Storage Came to the World

The need to save data and state in web applications/sites is very desirable since they work in a stateless manner. In the early days we could use cookies in order to save our data but this mechanism was very limited. The cookies had lots of limitations and downsides such as being sent in every HTTP request, 4KB of storage, can be disabled by the users and more. A need for a better mechanism was raised and Web Storage specification was born.

What is Web Storage?

Web Storage is a key/value dictionary that is stored in the web browser and persists your data even if you close the browser/browser tab (resembles the cookie mechanism). Unlike cookies Web Storage’s data is local to the web browser and isn’t sent to the server (no downgrade in traffic performance). In the specifications there is no limit to the amount of disk space that Web Storage can have but it is said that the browsers need to limit that amount. Web Storage is divided into two different storage objects:

sessionStorage – data in this storage is accessible to any page from the same site opened in that window.

localStorage – data in this storage spans multiple windows and lasts beyond the current session.

Each web application/site has its own dedicated storage.

Web Storage API

The Web Storage API include the following methods:

length – get the number of key/value pairs in the storage.

key(n) – returns the n’th key in the storage.

getItem(key) – returns the value of the provided key. If the item doesn’t’ exists it will return null. Pay attention that the returned item is a string! so if you saved data such as integer or boolean you will have to parse it.

setItem(key, value) – inserts a new value into the storage with the provided key.

removeItem(key) – removes the item that is connected to the provided key. If the key doesn’t exists the method do nothing.

clear – empty the storage from its data.

For example here is how you can get or set an item in the localStorage:

localStorage.setItem("key", "value);

var val = localStorage.getItem("key");

You can also use the storage without the get and set methods. You can do that by using the storage as a class with properties that you can access. The previous example can also be used as follows:

localStorage.key = "value";

var val = localStorage.key;

In some browsers the storage can also be treated as a dictionary (or javascript array) with an indexer such as you can see in this example:

localStorage["key"] = "value";

var val = localStorage["key"];

Currently, the indexer behavior isn’t part of the specification (but maybe it will be added).

Another aspect of the Web Storage is the storage event that is fired when a change occurs in the storage. That event is wired to the window object and is fired whenever setItem, removeItem or clear are being used. You can wire to that event with a function that receive an event parameter:

if (window.addEventListener) {

window.addEventListener("storage", handleStorageEvent, false);

} else {

// for IE versions below IE9

window.attachEvent("onstorage", handleStorageEvent);

};

function handleStorageEvent(eventData) {

// Do something

}

The eventData parameter in the previous example will hold the following members for your own use:

key – the key that is being changed.

oldValue – the old value of the key that is being changed.

newValue – the new value of the key that is being changed.

url – the address of the document whose key is being changed.

storageArea – the storage that is being affected by the change.

An Example of Use

In the following example I’m using the localStorage in order to save the number of page load events and to present them to the user:

This is a very simple example but it shows the use of the API methods like getItem, setItem and clear. As you can see the data is saved in a string manner so you’ll have to parse it in order to retrieve it. In the example I parse the counter number which is an integer using the parseInt method. When you will close the browser or tab and then open it again you will notice that the storage will persist the last counter.

Summary

Web Storage is a new specification that tries to target the lack of opportunities to store client side data. There are other ways to store data on the client such as cookies or using Google Gears with its embedded database which is based on SQLite. I hope that this introduction will help you to get started with a feature that you can use even today. For further information you can go to Web Storage specification on W3C site.