an intro to html5 localstorage

18

May

Intro

HTML5 'localStorage' is a mechanism to allow websites and applications to hold data on a client PC without using cookies or resorting to server side storage means. It persists across HTTP requests, has ample storage for most web based systems (5MB by default, compared to 4Kb with cookies) and is not sent between client and server with each request (like cookies).

This means we can speed up our applications by avoiding cookie usage (which are sent per request) and prevent unencrypted data being fired around the internet.

In terms of usage localStorage now has fairly wide ranging browser support, currently Firefox 3.5+, Safari 4+, IE8+, and Chrome. This means that realistically a fairly high propotion of websites and applications can use localStorage natively now. There are also some polyfills for IE6/7 if you search about and wish to leverage similar functionality.

This article will detail the usage of localStorage to store and retrieve simple string values, and then a complex object or an array.

Basic usage:

In order to begin using localStorage, we can reference it with an indexer as shown below:

localStorage["myName"] = "Doug";
var myName = localStorage["myName"]; //returns "Doug"

We can also use the 'getItem()' and 'setItem()' methods in a similar manner

localStorage.setItem("myName", "Doug");
var myName = localStorage.getItem("myName"); //returns "Doug"

As well as writing and storing variables, we can also call 'localStorage.length' to determine how many elements we have in our localStorage, 'localStorage.removeItem(key)' to remove a specific item and 'localStorage.clear()' to remove all the elements.

This is great! No databases, no complexity, simply write variables to the local store and get them back out!

Whoa there! We do have a few caveats when using local storage, including those mentioned below:

  1. All the data is stored as plain strings (by default), don't try to store sensitive information.
  2. localStorage can be accessed and cleared at any time by the user. Do ensure you cater for variables you expect to be there, to be missing at run time.

Complex objects

So now we've stored basic data, surely we can just store this right?

var myArray = [1,2,3];
localStorage["array"] = myArray;

...Well, no, not quite. Whilst we won't get an error, we cannot retrieve the data in this way, and if we try to, we will find that we have simply stored the toString() representation of the array.

This is because, as mentioned earlier, we can only store strings localStorage. Since this is the case, we need a better mechanism to store anything more complex, objects or arrays for example.

Fortunately, the changes needed are trivial. Using Javascript's native JSON support, we can use JSON.stringify() and JSON.parse() to convert our object/array into a JSON string which we can now place into localStorage.

E.g.:

var myArray = [1,2,3];
localStorage["anArray"] = JSON.stringify(myArray);

After we've stringified our array, we can retrieve it by parsing the JSON string back into a Javascript construct.

var ourArray = JSON.parse(localStorage["anArray"]);

Summary

We can pop up to 5MB of data in localStorage and have nearly universal browser support. Whilst we need to be aware that any user with local access to the browser can clear our storage at any time, we can be secure in the knowledge that this data cannot be intercepted en-route to the server (as it stays local) and also that other websites cannot overwrite our storage area (as it's specific to each domain).

And that's it! A Brief intro into HTML5 localStorage, it's a really simple, convenient method to store data. Any modern browsers support it and as developers we should be using this today in our applications where we require storage for non sensitive data.

Comments
Doug 5/18/2013
Bacon ipsum dolor sit amet short loin turducken kielbasa leberkas, t-bone capicola boudin meatball pancetta rump. Pork belly hamburger venison frankfurter chicken drumstick kielbasa prosciutto swine doner shoulder. Doner filet mignon beef bacon hamburger venison rump meatball ham hock sirloin pork belly. Chuck ground round kielbasa flank meatball salami. Tail pancetta ball tip flank fatback tongue venison filet mignon shoulder shank pork loin doner turducken pig. Brisket shankle flank meatloaf, bresaola corned beef kielbasa bacon tri-tip beef fatback ribeye tenderloin. Shoulder tongue t-bone ribeye kielbasa boudin drumstick beef ribs pork loin shank pork. Ball tip meatloaf leberkas pastrami sirloin, pork belly pork. Shoulder tail turducken leberkas. Turkey meatloaf filet mignon kielbasa capicola ground round. Tail tongue pork chop, short loin drumstick prosciutto corned beef brisket pastrami. Bacon prosciutto ham hock pastrami jowl sausage spare ribs turducken tail tenderloin chuck pancetta flank.
Doug 5/18/2013
Brisket shankle flank meatloaf, bresaola corned beef kielbasa bacon tri-tip beef fatback ribeye tenderloin. Shoulder tongue t-bone ribeye kielbasa boudin drumstick beef ribs pork loin shank pork. Ball tip meatloaf leberkas pastrami sirloin, pork belly pork. Shoulder tail turducken leberkas. Turkey meatloaf filet mignon kielbasa capicola ground round. Tail tongue pork chop, short loin drumstick prosciutto corned beef brisket pastrami. Bacon prosciutto ham hock pastrami jowl sausage spare ribs turducken tail tenderloin chuck pancetta flank.
doug 5/18/2013
comment
add comment
Captcha