O'Reilly

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:

sessionStorage.setItem('someKey','someValue');

...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?

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

  • 6 Things You Didn&#8217;t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving,...

Incredible Demos

  • HTML5 Input Types Alternative

    As you may know, HTML5 has introduced several new input types: number, date, color, range, etc. The question is: should you start using these controls or not? As much as I want to say "Yes", I think they are not yet ready for any real life...

  • CSS Sprites

    The idea of CSS sprites is pretty genius. For those of you who don't know the idea of a sprite, a sprite is basically multiple graphics compiled into one image. The advantages of using sprites are: Fewer images for the browser to download, which means...

Discussion

  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.”
    http://dev.w3.org/html5/webstorage/#security-storage

  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

    Hello,
    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?
    Thanks

  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);} );
    

    then

    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

  • Preventing Side Effects in JavaScript

    JavaScript is very dynamic these days but I still see a lot of legacy code, whether it be for optimal backward compatibility or simply that the code hasn't been maintained.  One of the practices that makes me cringe is coding that creates unwanted side effects.  What's a side...

  • Access Mac Camera by Command Line

    With all of my recent command line tutorials, I've really gotten excited about the shell's simplicity and realized the true power of using the underlying technology of pretty UIs.  Since I work from home, I spend a lot of time on video calls, so when...

  • Open Files from Command Line on OS X

    I'm as much of a fan of application UIs as anyone else but I'm finding myself working more and more from the command line lately.  Much of that is becoming obsessed with media manipulation but I'm forcing myself to use less UIs so that I...

  • Get Stock Quotes From Command Line

    When I conned my way into my first professional programming gig, I didn't really think much about money -- just that I was getting my foot in the door.  But as my career has gone on, I've been more aware of money, investing, and retirement.  I've recently...

  • Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...