Using HTML5 Web Storage
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.
sessionStorage.clear(); //everything gone!
A simple clear call -- that's it.
(Very) Basic Web Storage Usage Example
When the user clicks the sign out link, we ask them to come back soon!
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.
What are your thoughts about HTML5 Web Storage? Have you used this for any applications yet?