Using HTML5 Web Storage

By on  

HTML5 is the biggest buzz word in web development today.  The new features promised by HTML5 will be a huge boost to web developers looking to stop rigging up ways to make their websites better, faster, and more flexible.  One feature that's caught my eye is HTML5's Web Storage.  Web Storage provides a client-side method for saving session information.  Take a look at how Web Storage works!

Simple Web Storage Facts

  • Values can be any data type supported by the structured clone algorithm.
  • User agents should not expire data from a browsing context's session storage areas, but may do so when the user requests that such data be deleted, or when the UA detects that it has limited storage space, or for security reasons.
  • Storage items are available on the entire domain.

HTML5 Web Storage Methods

  • setItem(key,value): adds a key/value pair to the sessionStorage object.
  • getItem(key): retrieves the value for a given key.
  • clear(): removes all key/value pairs for the sessionStorage object.
  • removeItem(key): removes a key/value pair from the sessionStorage object.
  • key(n):retrieves the value for key[n].

Setting a Key/Value

There are two different methods for setting information into sessionStorage:


...or you could just use the shortcut method:

sessionStorage.someKey = 'someValue';

Getting a Value

There are two methods to retrieve a key/value pair as well:

sessionStorage.getItem('someKey'); //returns 'someValue'

...or simply reference the sessionStorage object:

sessionStorage.someKey; //returns 'someValue'

Removing a Key/Value

sessionStorage.removeItem('someKey'); //returns 'undefined' for someKey

All you need to do is provide the key to the removeItem method.

Clearing Storage

sessionStorage.clear(); //everything gone!

A simple clear call -- that's it.

(Very) Basic Web Storage Usage Example

<a href="javascript:;" onClick="if(sessionStorage && sessionStorage.getItem('name')) { alert('Come back soon, ' + sessionStorage.getItem('name')); }">Sign Out</a>

When the user clicks the sign out link, we ask them to come back soon!

Browser Support...Ugh

Like every other cool feature available today, browser support is a concern.  Internet Explorer did not support Web Storage until IE8 so you will need to create your own sessionStorage object/class (maybe with MooTools or Dojo?) if you want to support earlier IE browsers.

HTML5 Web Storage is very simple but very intriguing.  Since HTML5 Web Storage requires JavaScript, you wont want to use this for any mission critical application unless you want to force users to use a browser that supports the feature.

What are your thoughts about HTML5 Web Storage?  Have you used this for any applications yet?

Track.js Error Reporting

Upcoming Events

Recent Features

  • 5 Awesome New Mozilla Technologies You&#8217;ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

  • Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • Drag &#038; Drop Elements to the Trash with MooTools 1.2

    Everyone loves dragging garbage files from their desktop into their trash can. There's a certain amount of irony in doing something on your computer that you also do in real life. It's also a quick way to get rid of things. That's...

  • Degradable SELECT onChange

    Whenever I go to Google Analytics I notice a slight flicker in the dropdown list area. I see a button appear for the shortest amount of time and the poof! Gone. What that tells me is that Google is making their site function...


  1. André

    “Since HTML5 Web Storage requires JavaScript, you wont want to use this for any mission critical application unless you want to force users to use a browser that supports the feature.”

    I think this is really a concern of the past and no longer necessitates calling out, be it to clients or employers alike. What modern web-based applications really expect any kind of momentum without JS? Graceful degradation for non-JS users is nice and everything, but HTML5 without JS support is just HTML 4…

  2. @Andrè do not forget that there are still many people who can’t use javascript..,
    Take as example all the blind people who use a screen reader to surf the web. Probably new semantic tags proposed by HTML 5 will improve the efficiency of their screen readers, but i think that javascript will not work for them still…
    So, in my opinion, is always good to be prepared for some kind of js-less degradation when developing a web site…

  3. Although this HTML5 feature is supported only by few browsers this doesn’t mean that it cannot be used in web applications. However someday this will be covered by any browser vendor? We hope so.

    Actually I wrote a jQuery plugin that slightly extends the localStorage HTML5 property: http://www.stoimen.com/blog/2010/02/26/jquery-localstorage-plugin-alpha/

  4. I’m curious about the security implications. Data stored this way is stored in plain text that anyone who has access to the box can read, right?

    Is it domain-based so a phisher can’t phish your local data by doing something like: sessionStorage.getItem(‘visa’) or whatever.

  5. André

    @Loige: While you are absolutely correct, current trends are, unfortunately, leaving people with assistive devices by the wayside. I think the old rule of “support the lowest common denominator” worked for the Old Web but, moving forward, JS support is a must-have for the latest and greatest web apps.

    I’m not saying it’s the way to go, but even giants like Google trade proper semantics in favour of feature enhancement for the majority of their users. It’s the old 80/20 rule.

    @stoimen HTML5 itself is actually supported by most browsers. It’s really a less strict version of XHTML with a few more deprecated elements and a couple of new ones. Other than the multimedia additions, the new elements are purely for semantics.

  6. @cancel bubble: As I understand it, browsers link the localStorage to the host name. So, as the W3C draft spec puts it:

    “Different authors sharing one host name, for example users hosting content on geocities.com, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore recommended to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.”

  7. I don’t get all the hype….how is this different from a cookie?

  8. Hey i liked this post… I also put in a small post but it was about web storage… SQL in Javascript…. Hope you can find this useful too… http://mnesia.wikispaces.com/HTML5+and+webstorage

  9. @André: I’m not saying to avoid using js at all! This would be an awful error these days…
    However i think that the informative part of a website should always be reacheable also by people who can’t use javascript…
    Surely this kind of degradation will produce a lot of additional work, but i think that doing so you are going to increase the value of your site and theorically the provided informations become able to reach everybody in the world, also people who use screen readers or textual browsers.

    (sorry for my “italianized” english, I hope it’s clear enough :P)

  10. @cancel bubble: I always felt that storing _important_ data on the client side is a bad idea to start with. And web storage more or less does what cookies does, with the exception that the data isn’t sent with every http request and session storage (see blow) is window specific and being a little less restrictive (and with an interface that’s easier to use).

    Web storage offers local and session-store for data. Session being restricted to the current window/tab and only lives as long as it does and local storage being pervasive but domain-bound. (Though as far as I’ve read browser implementation doesn’t allow TLD access, but I’m far from sure about that).

    But even though it’s domain-based malicious javascript injected on the page will still do the trick.

  11. Thank you for your post! I’m currently learning HTML5/sessionStorage to use in applications. Just curious, as I’m trying to find a solution with no luck… can the values be sent in an email? Or are these values meant to be temporary/session-only? -Aileen

    • The pervasive storage is domain specific. You can still send it to the server with a post for further processing but why would you want to?

  12. akua o asamoah

    I am excited about HTML5. I like programming the web and want to try out some of the new features. I just started learning it today. How do I check the user’s browsers to make sure he or she has an HTML5 compatible browser on his or her system?

  13. Akua Asamoah

    I used the localStorage command to store a cookie and retrieve a cookie. I noticed that I was able to retrieve the stored value when I stored the cookie and then pressed retrieve button. However, I was not able to do this when I stored it, closed the browser, and then tried to retrieve it. It acted like a session cookie or a temporary cookie was stored instead of a persistent cookie. How do I make the cookie into a permanent or persistent cookie?

  14. Ciul

    What about StorageEvent usage with MooTools?
    Have tried to test it but doesn’t seems to work.

    window.addEvent("storage", function (ev) {console.log(ev);} );


    window.sessionStorage.setItem('key', 'value');

    but nothing happens :(

  15. shri

    how can see the local storage of any browser

  16. Mike Jabber

    There is a new javascript library called cupcake.js which supports both session and local storages. You can find it from http://www.rivindu.com/p/cupcakejs.html

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OâReilly Velocity Conference â New York

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...