Web Storage API: More Security, Efficiency and Capacity than Cookies [con't]
How Web Storage Works
The Web storage API stores data in the form of key/value pairs. The data type of the key can be a string; even an empty string is a valid key. There are different attributes and methods defined for the Web storage object. In this section I explain how you can store and retrieve data using Web storage.
The two methods setItem
and getItem
are used to store and retrieve values, respectively. SetItem
takes two arguments as key and value. GetItem
retrieves the value of the already stored item by taking key as an argument. Here is how you store a key and value in local storage.
Now to retrieve this value, you use this:
null
.
You can store data to session storage in the same manner. The methods remain the same, only the object changes to sessionStorage
.
As previously discussed, the difference between local storage and session storage is their relative scope and lifetime, so you need to choose where you want to store your data. If you are going to use stored data every time the visitor visits your website, then choose localStorage
. However, with something like an online ticket-booking system, you should use sessionStorage
.
The following demo script shows how to save and retrieve values in local and session storage. It works in Opera.
Other Web Storage Methods
These other methods provided in the storage interface will be helpful when you use storage API.
removeItem(key)
: This method will remove the value of the key provided from the storage. If the key does not exist it will returnundefined
/null
.clear()
: As the name indicates, this method clears the entire list in the object of the associate key/value pairs.Length
: This attribute returns the number of key/value pairs currently stored in the associated object.
The above methods and attributes can be used with both session storage and local storage objects.
Summary
Not all browsers have implemented Web storage as if now, but eventually they will. Despite the fact that an attacker can hack Web storage similarly to cookies and make false logins, Web storage certainly is another step closer to a safe Web.
Original: June 14, 2010