Java Reference
In-Depth Information
if(window.localStorage) {
localStorage.clear();
}
Every time a value is saved to local storage, a storage event is fired. Note that this event
is only fired on any other windows or tabs from the same domain, and only if the value of
the item being saved changes. The event object sent by the event listener to the callback
has a number of properties that provide information about the updated item:
key tells us the key of the item that changed
newValue tells us the new value to which it has been changed
oldValue tells us the previous value before it was changed
storageArea tells us if it is stored in local or session storage
The following piece of code will add an event listener that logs information about any
changes to the Web Storage:
addEventListener('storage', function(event) {
console.log("The " + event.key + " was updated from " +
event.oldValue + " to " + event.newValue " and saved in
" + event.storageArea) }, false);
That only strings can be saved might seem like a restriction at first, but by using JSON, we
can store any JavaScript object in local storage. For example, we could save the superhero
object that we created in the form in Chapter 8 by adding the following line of code to the
to the end of the makeHero() function:
if(window.localStorage) {
localStorage.setItem(hero.name, JSON.stringify(hero);
}
This will save the hero object as a JSON string using the name of the hero as the key. To
retrieve the superhero as a JavaScript object:
Search WWH ::




Custom Search