Storing JavaScript objects in html5 localStorage

There is a rising new age of HTML5, which comes with very nice features as video tag and localStorage. What localStorage is? In fact we have been waiting for long time to have something that give us the power of storing more and more on the client side. That’s because the net is becoming larger and therefore heavy.

Imagine if you have the possibility to store large JSON returned from an AJAX call on the client. That’s now reality with the localStorage object in HTML5 and it can be accessed with something like this code:

localStorage.setItem(key, value);
alert(localStorage.getItem(key));

Can we store entire objects?

Yes there is a way extending a bit the logic of the code above. The localStorage in fact stores only strings, but what about arrays and objects. You can additionally use JSON global objects and its two methods – stringify and parse:

var a = JSON.stringify({name:'obj'});
alert(JSON.parse(a));

Do browsers support all that?

Of course … not! localStorage is supported by Firefox 3.5+, Chrome 2+, Safari 4+ and MSIE 8+. The solution is not to rely on browser version, but to check for object existence, and than to combine both techniques:

localStorage.setItem('a', JSON.stringify({ name : 'obj' }));
alert(JSON.parse(localStorage.getItem('a')));

5 thoughts on “Storing JavaScript objects in html5 localStorage

  1. Is it possible to store an entire JS library like Jquery in local storage? If so can you help me? There is a reason for me doing this, I don’t want to use Cache…so maybe you can help me get it into localstorage.

    thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *