Saving state or values have never been easy on the web, especially on the client-side, and using cookies have been far from ideal. Enter DOM/Web Storage!
Web Storage is a W3C draft which covers exactly how saving information on the client-side should be done. It was initially part of the HTML 5 specification, but was then taken out to be independent. Web Storage, or the somewhat confusing popular name DOM Storage, is a great way to save information for the current session and window, or for returning users.
Types of storage objects
There are two types of storage objects:
sessionStorage, for the current session and window, and
localStorage, which will last between sessions. Here are a couple of code examples:
sessionStorage["name"] = "Robert"; var theName = sessionStorage["name"];
localStorage["occupation"] = "Web Developer"; var occupation = localStorage["occupation"];
- Reference to the object’s constructor.
- Get value of item with sent in name.
- Get length of the number of items
- Get remaining space for the storage object. Only seems to work in IE 8 – personally, I find this property very useful.
- Clears all items in the storage object.
- Get the name of the item at a certain position.
- Remove item with sent in name.
- Set item value with sent in name.
Web browser support
DOM Storage is supported in these web browsers:
- Internet Explorer 8
- Firefox 2 for
sessionStorage, 3.5 for
- Safari 4
I find it interesting that Opera nor Google Chrome doesn’t support this yet. Also worth mentioning is that since Firefox 2, there was support for something called
globalStorage. That is now obsolete, and replaced by
localStorage (although it isn’t exactly the same thing).
Data saving capacity
The space available for saving data is 5 MB in Firefox and 10 MB in IE 8 (not sure about the size in Safari 4, but probably 5 MB as well). Compare that to cookies, who offers 2 to 4 kb! Imagine the possibilities!
- DOM Storage – Mozilla Developer Center
- Introduction to DOM Storage
- DOM Storage – John Resig (a little outdated, since it goes into the obsolete globalStorage object instead of localStorage)
Progressively enhance today!
My suggestion to you is to play around with this today! Soon over half of the web browsers used on the market will support this, so it’s not only here to stay, it’s the ground some serious coding in terms of storing things. Just make sure to use progressive enhancement and have storage objects where it’s supported, and other options/fallbacks where it’s applicable.
Progressive enhance today, what you could have enhanced tomorrow!