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.

240<br />

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

Listing 9-15. Cross-Window Communication Using Storage<br />

// display records of new storage events<br />

function displayStorageEvent(e) {<br />

var incomingRow = document.createElement('div');<br />

document.getElementById("container").appendChild(incomingRow);<br />

}<br />

var logged = "key:" + e.key + ", newValue:" + e.newValue + ", oldValue:" +<br />

e.oldValue + ", url:" + e.url + ", storageArea:" + e.storageArea;<br />

incomingRow.inner<strong>HTML</strong> = logged;<br />

// add listeners on storage events<br />

window.addEventListener("storage", displayStorageEvent, true);<br />

After registering an event listener for the storage event type, this window will receive notification of<br />

storage changes in any pages. For example, if a browser window viewing<br />

http://www.example.com/browser-test.html that is currently browsing the same origin sets or changes a<br />

new storage value, the storageLog.html page will receive a notification. Therefore, to send a message to a<br />

receiving window, the sending window need only modify a storage object, and its old and new values<br />

will be sent as part of the notification. For example, if a storage value is updated using<br />

localStorage.setItem(), then the displayStorageEvent() handler in the storageLog.html page hosted at<br />

the same origin will receive an event. By carefully coordinating event names and values, the two pages<br />

can now communicate, a feat which has been difficult to accomplish before. Figure 9-12 shows the<br />

storageLog.html page in action, simply logging storage events it receives.<br />

Figure 9-12. The storageLog.html page logging storage eventsSummary

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

Saved successfully!

Ooh no, something went wrong!