HTML5 / Web Storage API

Posted by Alex on January 6, 2011 in Web Development

HTML5 unleashedThis API specification introduces the sessionStorage IDL attribute. This way, sites can add data to the session storage, and it will be accessible to any page from the same site opened in that window. It works similar to the cookies, but the main advantage of the API is that it allows storing more data, as it’s storage space is around 5MB depending upon user agent implementation.

Each Storage object provides access to a list of key/value pairs, which are sometimes called items. Keys are strings. Any string (including the empty string) is a valid key. Values can be any data type supported by the structured clone algorithm.

How it work?

When a new Document is created in a browsing context which has a top-level browsing context, the user agent must check to see if that top-level browsing context has a session storage area for that document’s origin. If it does, then that is the Document’s assigned session storage area. If it does not, a new storage area for that document’s origin must be created, and then that is the Document’s assigned session storage area. A Document’s assigned storage area does not change during the lifetime of a Document, even in the case of a nested browsing context (e.g. in an iframe) being moved to another parent browsing context.

Types of Storage

Session Storage
controls storing data for a single session on a single window.

Local Storage
controls data that’s accessible over multiple windows and that persists for longer than a single session

Declaring Storage Objects

Assigning values

<label>
<input type=”checkbox” onchange=”sessionStorage.article = true”>
Please submit your article
</label>

Set Item Method

sesionStorage.setItem(‘article’, ‘true’);

Other Methods

removeItem(key)
removes the item from the list

lenght()
return the length of the storage object array

key(n)
returns the name of the nth object in the array

clear()
empties all key / value pairs from the array

There is also a storage event, which allows you to assign event listeners and respond to any changes to store data. The storage event is fired on the window object whenever a change to the storage object occurs, and allows you to track:

  • storage object affected
  • the name of that’s been changed
  • the previous value of the key
  • the new value of the key
  • trigger page

For more information visit: W3 – Web Storage

Search

KaoZ Magazine Latest!

Blogroll