Treehouse

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?

ydkjs-3.png

Recent Features

  • 9 More Mind-Blowing WebGL&nbsp;Demos

    With Firefox OS, asm.js, and the push for browser performance improvements, canvas and WebGL technologies are opening a world of possibilities.  I featured 9 Mind-Blowing Canvas Demos and then took it up a level with 9 Mind-Blowing WebGL Demos, but I want to outdo...

  • 9 Mind-Blowing Canvas&nbsp;Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

Incredible Demos

  • Hot Effect: MooTools Drag&nbsp;Opacity

    As you should already know, the best visual features of a website are usually held within the most subtle of details. One simple trick that usually makes a big different is the use of opacity and fading. Another awesome MooTools functionality is...

  • Printing MooTools Accordion&nbsp;Items

    Sometimes we're presented with unforeseen problems when it comes to our JavaScript effects. In this case, I'm talking about printing jQuery and MooTools accordions. Each "closed" accordion content element has its height set to 0 which means it will be hidden when the...

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!