Over a million developers have joined DZone.

All you want to know about Web Storage

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

The wave of new functionalities known as HTML 5 offers you an in-browser storage medium to supplant many cookies' use cases. The Web Storage specification has been separated by the main HTML 5 one, and it is being supported in large part since Firefox 2 and Chrome 4, and even Internet Explorer 8 (although with some Api differences, as always).

Web Storage offers you some megabytes (5 to 10, depending on the implementation) of space for data that must stay on the client-side, and be accessible to JavaScript applications. Since these data are not kept in cookies, they won't be sent again and again on every HTTP request.

Local vs. session

There are two storages available to your JavaScript code: a local and session one.

Local storage is per-domain, and persists after the browser is closed. It's much like cookies, but of course is not transmitted to the server.

Session storage is window-wide (and by extension tab-wide), and the lifetime of its data is the windows's one. Its purpose is to support separate instances of the application running in different windows, a scenario that cookies will mess up.

Feature detection

First of all, it's important for your code to be aware if the browser it is executed in supports local storage.

You can test on window['localStorage'] to see if it is available without raising errors. As you probably know, the keys of the window object are equivalent to global variables, but accessing them from window won't result in a failure in case the object is missing. the same goes for window['sessionStorage']: the Apis of the two objects are totally equivalent and I would only describe the first from here on.

Api

A local storage is a key-value store, also known as associative array, map or dictionary. It has a set of methods you can us to manipulate the data in it: for example, getItem() and setItem() for accessing and mutating a single value.

You can also access values by treating the local storage object as an associative array, but this interface is not part of the standard.

Other utility methods are removeItem(), which deletes a value, and clear(), which deletes all values. For iterating over the storage, you can use its length property and its key() method. key() takes a number i from 0 to length minus 1, and returns the name of the i-th stored key.

Events

As a disclaimer, before reading this paragraph, consider that the storage event support is missing in many browsers. From my tests, even Firefox 4 and Chrome do not support fire this event. In the middle of 2010, only Opera supported this event.

The storage event is (read: should be) fired as a StorageEvent object, which contains some interesting keys: key (the key accessed), oldValue, newValue, and url (page that originated the event).

Events support is read-only part of the Api: it cannot cancel the current modification event and revert the storage.

Show me the code

I recollected everything you need about the syntax and semantics of Web Storage in a JsTestDriver exploratory test. The last test failed, due to lack of support for the storage event.

TestCase("HTML 5 local storage usage exploratory tests", {
    setUp : function () {
        this.localStorage = window['localStorage'];
        this.localStorage.clear();
    },
    "test storage can store values by key" : function () {
        this.localStorage.setItem('myKey', 'myValue');
        assertEquals('myValue', this.localStorage.getItem('myKey'));
    },
    "test storage can be iterated upon" : function () {
        this.localStorage.setItem('key1', 'value1');
        this.localStorage.setItem('key2', 'value2');
        var result = [];
        for (i in this.localStorage) {
            result.push(this.localStorage[i]);
        }
        assertEquals(['value1', 'value2'], result.sort());
    },
    "test storage can remove items one by one" : function () {
        this.localStorage.setItem('key1', 'value1');
        this.localStorage.setItem('key2', 'value2');
        this.localStorage.removeItem('key1');
        assertNull(this.localStorage.getItem('key1'));
        assertEquals('value2', this.localStorage.getItem('key2'));
    },
    "test storage events can be used to listen to changes in the store" : function () {
        // with IE it will be onstorage or something different, rely on a JS framework in real code
        this.localStorage.setItem('myKey', 'myOldValue');
        var callbackCalled = false;
        window.addEventListener('storage', function(e) {
            assertEquals('myKey', e.key);
            assertEquals('myOldValue', e.oldValue);
            assertEquals('myNewValue', e.newValue);
            callbackCalled = true;
        }, false);
        this.localStorage.setItem('myKey', 'myNewValue');
        assertTrue(callbackCalled);
    }
});

Alternatives

The HTML 5 tsunami also brings other possibilities for local storage.

Web SQL Databases were, in fact, in-browser SQL database to be accessed via JavaScript. Since every browser converged on Sqlite for implementing it, without a specification of the SQL dialect (SQLITE 2.x? 3.x?), the W3C decided to scrap the standard. Some fellows were already building an ORM on top of Web SQL Database.

Indexed DB has instead been pushed by Mozilla and Microsoft as a viable substitute, due to the impasse of Web SQL Database. It is an object database, without a mandatory declarative query language on top of it.

Conclusion

Local and session storages makes our browsers even smarter than they are now. Be wary of not overusing it however: otherwise your data won't really be on the cloud anymore (and if your laptop is stolen or destroyed like in Google's video... your data go with it).

This kind of storage is also resettable, like for cookies, at the user's choice, or with a browser change. Yet connectivity is not always guaranteed in life: won't you be pleased of being able to save your work when you're on an airplane or train?

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}