Web Storage in HTML5

We have some really clever people in our office, all working on different things in their spare time. So it is quite nice to go around and see what people are looking at, and I saw someone playing around with HTML5 bits and bobs. I quite liked the Web Storage functionality so decided to have a go knocking up a little feature for our CRM system.

So, first of all I read the specification which is currently still work in progress, however most modern browsers already support Web Storage. The feature I wanted to write was to keep a local history of accounts viewed in our CRM. So you could click a tab and out popped the last x accounts that have been viewed and you could then click them to revisit the account. The example is a little contrived and you could easily do this in a multitude of other ways, but today I wanted to learn Local Storage.

The first issue that I needed to consider was not all browsers support this yet, so if it wasn’t supported I was simply not going to show the history tool. To find out if the browser is support you can write:

# See if the Local Storage feature is available in the browser
    var myStorage = {}

    myStorage.isLocalAvailable = function () {
        if ('localStorage' in window && window.localStorage !== null) {
            return true;
        } else {
            return false;
        }
    };

The main aspect here is the new ‘localStorage’ variable that we can check exists. This is the object we can use to deal with local storage. From now on we can wrap the functionality with this check to understand if we can use local storage or not. Some other wrapper functions I wrote were to get/set the item in local storage, simply so we had a common entry point. This is an advantage because if you wanted to use Session Storage rather than Local Storage there are less places to change the code. So here are my getter/setter functions

# Getter
    myStorage.getLocalItem = function (key) {
        if (myStorage.isLocalAvailable()) {
            return $.parseJSON(localStorage.getItem(key));
        } else {
            return null;
        }
    };

    # Setter
    myStorage.setLocalItem = function (key, value) {
        if (myStorage.isLocalAvailable()) {
            localStorage.setItem(key, JSON.stringify(value));
        }
    };

The reason we are stringifying and JSONifying is because the Local Storage can only have key/pair values of strings. I wanted to store an array of objects, which it simply doesn’t like. It took myself and Dan a fair amount of digging to find this out.

The last code snippet is the actual guts of the work, which looks for the details I want to store and then sets and gets them

myStorage.init = function () {
        //Local storage checks
        if (myStorage.isLocalAvailable()) {
            var username = $('#historyPopup > #historyUsername:first').html();
            var id = $('#historyPopup > #historyId:first').html();
            if ($('#historyBar').hasClass('hide')) {
                $('#historyBar').removeClass('hide');
            }

            // Create the HistoryItem
            var item = new HistoryItem(username, id);

            try {
                var items = [];
                var localItems = null;

                localItems = myStorage.getLocalItem('crmHistory');
                if (localItems !== null) {
                    items = localItems;
                }

                $(items).each(function () {
                    if (this.id === item.id) {
                        items.splice($(items).index(this), 1);
                    }
                });

                if (item.username !== null) {
                    if (items.length === 10) {
                        items.shift();
                    }
                    items.push(item);
                }

                items.reverse();

                $(items).each(function () {
                    $('#historyPopup > ul').append(
                            '