In the
Local Storage API in HTML 5 , i blogged about
localStorage
JavaScript object that you can use for storing data on the client side. The data stored using
localStorage
API would be available across browser restart and all the windows/tabs opened from that domain.
The HTML5 specification also provides
sessionStorage
object that has same interface as the
localStorage
object with the difference that the data stored using the
sessionStorage
API stays only during lifetime of browser session, so you will loose it when you close the browser window or even if you open a new browser window.
I wanted to try this out so i changed the
localStorage
code to use
sessionStorage
instead of
localStorage
object, my code looks like this
<!doctype html>
<html>
<head>
<script>
window.onload =function(){
if(window["sessionStorage"]){
// Inserting or updating a key/value
var currentTime = new Date();
sessionStorage.setItem("key1","First test value" + currentTime.getTime() );
if(sessionStorage.getItem("key2") == null)
sessionStorage.setItem("key2","Second test value"+ currentTime.getTime());
document.getElementById("key2Value").innerHTML = sessionStorage.getItem("key2");
// Getting value of key from session storage
console.log(sessionStorage.getItem("key1"));
//Removing a key from the session storage
sessionStorage.removeItem("key1");
console.log(sessionStorage.getItem("key1"));
//Iterate through all the keys and print them in key=value format
for( var key in sessionStorage)
console.log(key + " = "+sessionStorage[key]);
//Iterate through all the keys and print them in key=value format
for (var i = 0 ; i < sessionStorage.length;i++){
var keyName = sessionStorage.key(i);
console.log(keyName +" = "+ sessionStorage[key]);
}
//Removing everything
// sessionStorage.clear();
}else{
alert("Browser does not support sessionStorage");
}
}
</script>
</head>
<body>
<div id="key2Value"></div>
</body>
</html>
I made a change to check value of key2 if it exists do not set the value and display it on page. Then i opened two different tabs in same browser and keep refreshing page i could see that two different tabs got different values for the same key.
No comments:
Post a Comment