HTML5 Session and Local Storage

By | 18 August, 2013

Traditionally when one needs to store some information client-side, the first thing which comes to our mind is, as the popular monster says, cookies! This has been the approach used during the last years. However, with the recently arrival of HTML5 the web browsers which support this technology allow developers to store information in two similar but different stores: SessionStorage and LocalStorage.
The main difference between them is that SessionStorage keeps information while the user session is active, yet LocalStorage keeps it until users delete it manually. Therefore they can be used for different purposes.
Regarding the ShoppingCart app I’ve talking about in the latest posts, when the user clicks the refresh button in his browser, the app loses all the client-side information that was generated by the user, clicking around during his activity in our site. To avoid this undesirable behavior, we can used SessionStorage to keep the information safe until the user feels like quitting our site.
A very simple implementation is the following:

var updateStorage = function () {
        if (typeof (user) !== 'undefined') {
            sessionStorage.setItem('user', JSON.stringify(user));
            sessionStorage.setItem('basket', JSON.stringify(basketItems));
        }
};

Using the built-in Chrome extension for developers we can easily see the data that are been passed and stored in this storage:

To finish our solution we just need to get our data back, which we can do by using this method:

var loadLoggedInUser = function () {
        user = JSON.parse(sessionStorage.getItem('user'));
        basketItems = JSON.parse(sessionStorage.getItem('basket'));

        if (basketItems == null)
            basketItems = new Array();

        displayUserLoggedInPanel();
    };

Eventually there are some more ways to store information client-side and it’s likely that some others we’ll emerge soon. Due to the growing development of applications that are using more and more client-side logic. For instance we can talk about IndexDB which is not widely spread yet because of some incompatibility issues in several web browsers.

Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.