SessionStorage is an alternative to session cookies, but more powerful. The HTML5 storage API defines persistent data storage of key-value pair data in Web clients. The HTML5 Storage API improves upon HTTP session and local cookies that you are likely to be already familiar with. While cookies are limited to 4KB, the new standard allows for more space. The size depends on the browser, but is generally in the MB rather that KB range. HTML5 provides for two types of storage: persistant localStorage, and unique per open window/tab sessionStorage. Today we’ll focus on sessionStorage.
Session storage is accessible to any page from the same site opened in that window. If the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object.
Cookies are sent to the server with every HTTP request. Session data, however, isn’t sent automatically, reducing the size of every request. The developer determines which key-value pairs need to be sent with each request.
Okay that example explains how session storage is different from cookies… but is there not a slightly more practical example to talk about? I’m just thinking what storefront is ever going to think of what you just described as a desirable scenario that they’ll want to support (or care about)?
Perhaps something like the ability to test websites by logging in as different users as the same time from different tabs, or? just something that is a bit more practical would help I think…
sessionStorage should be used to store temporary data related to a single browser window as it ceases to exist after the window is closed.
The sessionStorage object has five methods and one property:
- setItem(key, value) – sets the value for the given key. For example, define the session variable with:
sessionStorage.setItem('keyname', 'data value')
- getItem(key) – retrieves the value for the given key. Returns null if the key does not exist.
- removeItem(key) – removes the key and its associated value. Unset the value with:
- key(position) – returns the key for the value in the given numeric position.
- clear() – removes all key-value pairs. Clear all the key value pairs with:
- length – The length property indicates how many key-value pairs are currently stored in sessionStorage.
Using sessionStorage is extremely easy. It is like defining and using a regular variable, except that it needs to be prefixed with sessionStorage.
For more information on sessionStorage, see http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/