Java Reference
In-Depth Information
closes the browser (like a cookie without an expiration date). But in most cases, you want to store
data that persists between visits, and that is local storage's purpose. Other noteworthy features of
web storage are:
It stays within the browser and is not transmitted to the server. It is storage for JavaScript
developers.
It provides significantly more storage space. Chrome and Firefox support 5MB per domain.
IE supports 10MB.
The data stored in local storage never expires; it remains until you or the user deletes it.
Note This section focuses on local storage, but you can apply the same
concepts to session storage.
The data stored in web storage is associated with a unique name. In technical terms, we refer to this
name as a key , and the data associated with a key is referred to as the value . Together, we refer to
the key and its value as a key/value pair.
You access local storage using the localStorage object (session storage is accessed through
sessionStorage ), and it makes it easy to set, get, and remove data.
setting data
The localStorage object exposes a method called setItem() , and its purpose is to set a value
associated with a given key. It's very simple to use, as shown here:
localStorage.setItem("userName", "Paul");
The first argument passed to setItem() is the key; the second is the value associated with that key. In the
case of this code, the value of Paul is stored in local storage and is associated with the key of userName .
You can also set data using the more traditional object.propertyName syntax, like so:
localStorage.userName = "Paul";
The result of this code is identical to the previous setItem() example; the value of Paul is set for the
key of userName .
If the results are identical, why use setItem() ? The answer is that you don't have to unless your key
is an invalid JavaScript identifier. For example, let's say you want to use the key user name . That's
impossible to use as a property name:
localStorage.user name = "Paul"; // invalid!
But you can use " user name " as a key with the setItem() method:
localStorage.setItem("user name", "Paul");
In most cases, you won't use setItem() , but it is there to use if and when you need to.
 
Search WWH ::




Custom Search