Having fun with HTML5 — Local Storage and Session Storage

HTML5 includes two new ways to store data on the client – local stor­age and ses­sion stor­age. Local stor­age has no time lim­it on how long the data should be kept around, ses­sion stor­age on the oth­er hand (as the name sug­gests) stores data for only one ses­sion.

Tra­di­tion­al­ly you can store data on the client using cook­ies, but they are not suit­ed for stor­ing large amounts of data because every­thing gets sent back to the serv­er on every request and hence slows down the roundtrip and mak­ing the user expe­ri­ence less enjoy­able.

Using the new stor­age meth­ods, data is only passed on when asked for and it’s there­fore pos­si­ble to store large amounts of data with­out slow­ing down the site. The data is also sand­boxed and a web­site can only access data stored by itself, you can use javascript to set and get data from the rel­e­vant stor­age.

Browser Support Detection

A brows­er that sup­ports HTML5’s local stor­age will have a local­Stor­age prop­er­ty on the glob­al win­dow object, you can write your own func­tion to check for the exis­tence of and valid­i­ty (not null) of the local­Stor­age prop­er­ty, or use a third-par­ty library like Mod­ern­izr.

Mod­ern­izr is an open source, light weight javascript library that detects sup­port for many HTML5 and CSS3 fea­tures, when it runs it cre­ates a glob­al object called Mod­ern­izr. To check for local stor­age sup­port, all you need to do is to check the boolean flag for local stor­age:

if (Modernizr.localstorage) {
    // browser supports local storage
}
else {
    // browser doesn't support local storage
}

or sim­i­lar­ly for ses­sion stor­age:

if (Modernizr.sessionstorage) {
    // browser supports local storage
}
else {
    // browser doesn't support local storage
}

API

The full API spec­i­fi­ca­tion for the local­Stor­age and ses­sion­Stor­age objects can be found here. At the time of writ­ing, this is how the com­mon Stor­age inter­face look:

image

Demo

I’ve put togeth­er a quick demo here to illus­trate how to detect and use the local and ses­sion stor­age to get, set, remove and clear stored items (well, basi­cal­ly, cov­ers each of the avail­able meth­ods on the Stor­age inter­face above).

The page itself is sim­ple and crude, just a cou­ple of <div> and most impor­tant­ly two tables which I use to show all the key val­ue pairs stored in the local and ses­sion stor­age:

image

Page Load

When the page fin­ish­es load­ing, I call the Mod­ern­izr object to find out if the cur­rent brows­er sup­ports local and/or ses­sion stor­age, if not, hide the rel­e­vant <div> ele­ments so the tables are not even shown on the page:

$(document).ready(function () {
    // hide the storage divs if browser doesn't support local storage or session storage

    if (Modernizr.localstorage && Modernizr.sessionstorage) {
        $("#detectionSpan").html("Your browser supports both local and session storage");
    } else {
        if (!Modernizr.localstorage) {
            $("#detectionSpan").html("Your browser doesn't support local storage");
            $("#localStorageDiv").hide();
        } else {
            $("#detectionSpan").html("Your browser doesn't support session storage");
            $("#sessionStorageDiv").hide();
        }
    }
    showKeys();
});
Populate Tables

The showKeys() func­tion pop­u­lates the localTable and ses­sionTable tables with the keys in the cor­re­spond­ing stor­age if and only if the stor­age type is sup­port­ed by the brows­er:

// show the keys currently held in the local and session storage
function showKeys() {
    if (Modernizr.localstorage) {
        showStorageKeys("local", "#localTable");
    }
    if (Modernizr.sessionstorage) {
        showStorageKeys("session", "#sessionTable");
    }
}

// show the keys currently held in the specified type of storage in the specified table
function showStorageKeys(type, table) {
    // get the specified type of storage, i.e. local or session
    var storage = window[type + 'Storage'];

    // remove the rows in the specified table before we start
    $(table + " > tbody > tr").remove();

    // loop through the existing keys in the storage and add them to the TBODY element as rows
    for (var i = 0; i < storage.length; i++) {
        var key = storage.key(i);
        var value = storage.getItem(key);
        $(table + " > tbody:last")
            .append("<tr><td>" + key + "</td>" +
                    "<td>" + value + "</td>" +
                    "<td><input type='submit' value='Remove' onclick='removeItem(\"" + type + "\", \"" + key + "\")'/></td></tr>");
    }
}
Introducing the new placeholder attribute

You might have noticed that the two text box­es had place­hold­er text sim­i­lar to that famil­iar search box in Fire­fox:

text boxes with place holder text Firefox search box

This is done using HTML5’s place­hold­er attribute for the <input> tag:

<input id="keyText" placeholder="Enter key"/>
<input id="valueText" placeholder="Enter value"/>

Nice and easy, eh? ;-)

Setting an item

To add a new key val­ue pair or update the val­ue asso­ci­at­ed with an exist­ing key, you just have to call the setItem method on the intend­ed stor­age object:


// adds a new key to both local and session storage
function setKey() {
    var key = $("#keyText").val();
    var value = $("#valueText").val();

    if (Modernizr.localstorage) {
        localStorage.setItem(key, value);
    }
    if (Modernizr.sessionstorage) {
        sessionStorage.setItem(key, value);
    }
    showKeys();
}
Removing an item

Ear­li­er in the showStorageKeys(type, table) func­tion, I added a row to the rel­e­vant table for each key val­ue pair in the stor­age includ­ing a but­ton with a han­dler for the onclick event. The han­dlers are cre­at­ed with the cor­rect stor­age type (“local” or “ses­sion”) and key for the cur­rent row baked in already so that they will call the removeItem(type, key) func­tion with the cor­rect para­me­ters:

// removes an item with the specified key from the specified type of storage
function removeItem(type, key) {
    // get the specified type of storage, i.e. local or session
    var storage = window[type + 'Storage'];
    storage.removeItem(key);
    showKeys();
}
Clearing all items

Final­ly, the ’”Clear” but­tons under­neath the tables call the clear­LocalKeys() and clearS­es­sion­Keys() func­tion to remove all the key val­ue pairs in the cor­re­spond­ing stor­age:

function clearLocalKeys() {
    clearKeys("local");
}

function clearSessionKeys() {
    clearKeys("session");
}

// clear all the held keys in the specified type of storage
function clearKeys(type) {
    // get the specified type of storage, i.e. local or session
    var storage = window[type + 'Storage'];

    // clear the keys
    storage.clear();

    showKeys();
}

So that cov­ers all the inter­est­ing bits about the demo and all and all pret­ty straight for­ward and easy to imple­ment, admit­ted­ly I’m a javascript novice so if you feel any of this could be done bet­ter please feel free to point out to me!