25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Listing 9-14. JSON Object Storage<br />

<br />

var data;<br />

function loadData() {<br />

data = JSON.parse(sessionStorage["myStorageKey"])<br />

}<br />

function saveData() {<br />

sessionStorage["myStorageKey"] = JSON.stringify(data);<br />

}<br />

window.addEventListener("load", loadData, true);<br />

window.addEventListener("unload", saveData, true);<br />

<br />

CHAPTER 9 ■ USING THE <strong>HTML</strong>5 WEB STORAGE API<br />

As you can see, the script contains event listeners to register handlers for load and unload events in<br />

the browser window. In this case, the handlers call the loadData() and saveData() functions,<br />

respectively.<br />

In the loadData() function, the session storage area is queried for the value of a storage key, and that<br />

key is passed to the JSON.parse() function. The JSON.parse() routine will take a previously saved string<br />

representation of an object and reconstitute it into a copy of the original. This routine is called every<br />

time the page loads.<br />

Similarly, the saveData() function takes a data value and calls JSON.stringify() on it to turn it into a<br />

string representation of the object. That string is, in turn, stored back into storage. By registering the<br />

saveData() function on the unload browser event, we ensure that it is called every time the user navigates<br />

away or shuts down the browser or window.<br />

The practical result of these two functions is that any object we wish to track in storage, no matter if<br />

it is a complex object type, can be stored and reloaded as users navigate in and out of the application.<br />

This allows developers to extend the techniques we have already shown to nontext data.<br />

A Window into Sharing<br />

As alluded to in an earlier section, the ability for <strong>HTML</strong>5 Web Storage events to fire in any window<br />

browsing the same origin has some powerful implications. It means that storage can be used to send<br />

messages from window to window, even if they are not all using the storage object itself. This, in turn<br />

implies that we can now share data across windows that have the same origin.<br />

Let’s see how this works using some code samples. To listen to cross-window messages, a simple<br />

script needs only to register a handler for storage events. Let’s assume that a page running at<br />

http://www.example.com/storageLog.html contains the code shown in Listing 9-15 (the sample file<br />

storageLog.html for this example is also located in the code/storage folder):<br />

239

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!