HTML and CSS Reference
In-Depth Information
FIGURE 1-51 Storing items in and retrieving them from web storage
Now, if you close the browser and then reopen your page, the items are still available in
local storage. Try replacing all uses of localStorage with sessionStorage . This time notice that
closing the browser automatically clears out any data in the storage.
The benefit to using the Web Storage API instead of cookies is that the data resides
locally and stays local. The data doesn't get sent back and forth to and from the server, as
is the case with cookies. Data stored in web storage is organized by root domain . The space
allotment is available on a per-root domain basis. For example, domains such as localhost or each get their own secure web storage space.
As defined by the API, web storage allows storage only of key/value pairs where the key
and the value component are stored as a string. If you need to store more complex objects in
web storage, you can use a few techniques. For example, add the following code right before
the first call to LoadFromStorage in the onload event:
var customer = new Object();
customer.firstName = "Rick";
customer.lastName= "Delorme";
customer.shirtSize = "XL";
localStorage.setItem("cart1", JSON.stringify(customer));
This code creates a custom object to represent a customer browsing the site and sets that
customer's shirt size. This information is to be kept and used locally, so it doesn't need to be
posted to the server. Local storage is a great solution for this. However, to store the custom
object in local data, you need a method to convert the custom object to a string that matches
the local storage model. This is where JavaScript Object Notification (JSON) can come in
handy. You can serialize the object into a JSON string, give it a key, and then store it in web
storage. When you run this application now, it shows the customer object represented as a
JSON string in Figure 1-52.
Search WWH ::

Custom Search