Monday, 8 April 2013

Store Data with sessionStorage

Recently, I began working on a web application that relies heavily on client-side scripting. At some point, I needed to store some key value and use it again within the same context. Sounds easy, no? But hey, I need a client-side solution; so no sessions. And cookies won’t do since they can be disabled by the user; and they get sent to the server on every HTTP request, among other downsides.

After researching our options, we found about a neat solution that does fit the situation: sessionStorage.

What is sessionStorage?

sessionStorage is one of 3 client-side data storage options introduced with HTML5. The 3 main options are sessionStorage, localStorage, and client-side databases.

It is basically an object that exists as a property of the “windows” object. You can use it to store up to 5M [most browsers] or 10M [IE] of key-value pairs to be used locally.

The sessionStorage object persists in the window [tab] in which it is being used. If you close the tab [the top-level browsing context] it will not persist. Though, it will still persist if you refresh the browser tab, or navigate to another site then use “Back” to return to the same window it is defined within.

In short, the data in the sessionStorage object is deleted when the tab [window] is closed, or upon deleting it explicitly. This makes sure the data is not stored indefinitely.

API Methods and Example Usage

The sessionStorage object ships with the following five methods:
  • getItem(key): retrieves the value for the given key or null if the key doesn’t exist.
  • setItem(key, value): sets the value for the given key.
  • removeItem(key): removes the key completely.
  • key(position): returns the key for the value in the given numeric position.
  • clear(): removes all key-value pairs.

And one property, length, used to indicate how many key-value pairs are currently stored in the sessionStorage object.

The most straightforward example to showcase sessionStorage usage would be:

//Setting a key “Name” to the value “Alice” and saving it in the sessionStorage object.
  • sessionStorage.setItem("Name", "Alice"); 
//Retrieving the value of “Name”.
  • alert(sessionStorage.getItem("Name")); 

sessionStorage vs. Cookies

The main advantages of sessionStorage over Cookies are:
  • Cookies don’t allow big objects. sessionStorage on the other hand allows for 5M [most browsers] or 10M [IE] of data.
  • Cookies get sent to the server with each HTTP request which increases the traffic; not the case with sessionStorage.

Browser Support

According to Wikipedia, sessionStorage is supported in IE8+, Firefox 3.5+, Safari 4.0+, and Chrome 4.0+

Further Reading

You can refer to this very good article on NCZOnline for more information about this important and interesting topic.

No comments:

Post a comment