File Under: HTML5, JavaScript

How to Use HTML5′s Local Storage Tools Today

Cookies have long been the primary way to save information to a user’s browser. Whether it’s login info, preference settings or generic form data, most web developers turn to browser cookies. But HTML5 offers a new way to store data in the browser — the client-side storage APIs.

To take advantage of client-side storage you just need to write a bit of JavaScript. One of the best things about localStorage is how easy it is to use. For example, say you want to store a user’s favorite website. Here’s the JavaScript code you’d need to do that:

localStorage.setItem('favoriteSite','Webmonkey.com');

Then to access the stored info you just call it by name:

localStorage.getItem('favoriteSite');

Unfortunately, like much of HTML5, older browsers don’t know what to do with localStorage calls in your code. That does not mean, however, that you can’t use localStorage today, it just means you need a good fallback option for browsers that aren’t up to handling HTML5.

Developer Louis Remi has a post over on the Mozilla Hacks blog outlining how you can get started with localStorage and handle older browsers at the same time. The trick is to use Store.js as a fallback shim for older browsers.

Remi has already turned his experiment into a JQuery plugin, Persival, which allows you to create a web form capable of withstanding accidental tab closings or browser crashes.

If you’re just getting started with localStorage, be sure to check out Christian Heilmann’s write up over at Smashing Magazine which makes a good primer on both the why and how of HTML5′s localStorage API.

Of course localStorage has a dark side as well. It’s one of several tricks behind the rather scary “evercookie,” so, as with all things powerful, use responsibly.

Storage container photo by Louis Vest/Flickr/CC

See Also: