Saturday, July 30, 2011

localStorage

localStorage can be used store values corresponding to their key name similar to a session variable, using the method localStorage.setItem("key","value"), and to view the value we can simply use the method localStorage.getItem("key"). Just write the below code under a script tag and see the use of localStorage.


if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
try {
localStorage.setItem("name", "Hello World!"); //saves to the database, "key", "value"
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}

document.write(localStorage.getItem("name")); //Hello World!
//localStorage.removeItem("name"); //deletes the matching item from the database
//}





localStorage.removeItem("key") can be used to remove the value corresponding to the key once it is used. Calling setItem() with a named key that already exists will silently overwrite the previous value.