HTML5 Web Storage
HTML5 has recently taken the spotlight in the web development world, promising new features to improve the way we experience the web. One of the main features introduced with HTML5 is client-side storage with Web Storage. This allows the developer to store session information about the user on their computer so when they return the site will be better acustomed to them, think of it as Web Cookies on steroids. Anyways enough chitchat, lets dive into some code!
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:
sessionStorage.setItem('someKey','someValue');
What this does is it sets “someKey” with “someValue”.
Now you may also use another method to accomplish the same task.
sessionStorage.someKey = 'someValue';
Calling a Value:
There are two methods for calling key/value pais as well:
sessionStorage.getItem('someKey'); //returns 'someValue'
and
sessionStorage.someKey; //returns 'someValue'
Both return the same value.
Removing a Key/Value from the Session Storage:
sessionStorage.removeItem('someKey'); //returns 'undefined' for someKey
All you need to do is provide the key to the removeItem method
Clearing Session Storage:
sessionStorage.clear(); //deletes everything
Sample Code:
<a href="javascript:;" onClick="if(sessionStorage && sessionStorage.getItem('user')) { alert('Come back soon, ' + sessionStorage.getItem('user')); }">Sign Out</a>