Tuesday, January 22, 2013

HTML5 localStorage and sessionStorage

The localStorage and sessionStorge from HTML5 are very helpful
in in saving data in Key/Value pair and provide a replacement
for our old buddy Cookies.

Now lets see it basics

HTML5 Storage Object Methods

1) getItems(key)--> key is the sting value.
2) setItems(key)--> key is the sting value.
3) removeItem(key) key is the sting value.
4) key(n) --> n is the name of the key and return type is value of that key.
5) clear().


Explanation for localStorage.

We have a div with the name "result".
we set its text (innerHtml) to Last Name:in the script section.
typeof(Storage) is used to check if the browser support Storage.

1) localStorage.setItem('lastname','Smith'); is used to set the values.

2) document.getElementById("result").innerHTML="Last Name:" + localStorage.lastname; is used to set the values in div.

3) localStorage.clear(); is used to clear all the keys and vlues in localStorage.


The same is with sessionStorage the only difference is it will loose values when the browser session is closed.

No comments: