Geeks With Blogs
Phubar Baz Musings of an HTML5 Programmer

I've been working on an HTML5 application called Virtual Hamronograph. Since JavaScript can't save to the local file system I use localStorage to allow users to save harmonographs. I find this to be a good alternative. If you don't know, localStorage is a new global object in HTML5 that allows you to save up to 5MB of data in the browser. You save values by calling localStorage.setItem(key, value). You get values by calling localStorage.getItem(key). You can remove items by calling localStorage.removeItem(key). To get a list of all keys you can iterate over the localStorage object, just like you would any other object. Unfortunately localStorage only stores strings (not objects).

That's where JSON comes in. JSON is also a new global object in HTML5. It is used to convert JavaScript objects to and from JSON strings. You convert an object to a string by calling JSON.stringify(object). You convert a json string to an object by calling JSON.parse(json). Now you have a way to get objects in and out of local storage.

One thing to note is that the same localStorage is shared by all apps in the same domain (scheme + host + port). So if you have multiple web apps on your web site you could have the chance of overwriting some other apps data if it has the same key. To guard against that I prepend all of my keys with the apps name. So for example in my harmonograph app I prepend all keys with "Harmonograph.".

You can look at what is in localStorage in your browser's development tools. For instance, in Chrome if look under the Resources page there is a Local Storage item in the tree. Expand that and you can see all of the items in local storage for your site.

Happy coding!

Posted on Monday, October 17, 2011 12:05 PM | Back to top

Comments on this post: HTML5 localStorage and JSON

# re: HTML5 localStorage and JSON
Requesting Gravatar...
Great article. Useful information. Thanks for Posting.
Left by sundar on Oct 18, 2013 9:09 AM

Your comment:
 (will show your gravatar)

Copyright © PhubarBaz | Powered by: