Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 11 USING THE STORAGE APIS

libraries built on top of the standard. The Indexed Database itself is simply too complex for most web developers to use it in its current form.

This begs the question: if developers end up needing third-party libraries to take advantage of the built-in storage API, wouldn’t it be prudent to simply build that storage in native code rather than as a JavaScript library that must be downloaded and interpreted at runtime? Time will tell if the Indexed Database suits the needs of the majority.”

Practical Extras

Sometimes, there are techniques that don’t fit into our regular examples but nonetheless apply to many types of HTML5 applications. We present to you some short, but common, practical extras here.

JSON Object Storage

Although the specification for Web Storage allows for objects of any type to be stored as key-value pairs, in current implementations, some browsers limit values to be text string data types. There is a practical workaround, however, due to the fact that modern versions of browsers contain built-in support for JavaScript Object Notation (JSON).

JSON is a standard for data-interchange that can represent objects as strings and vice-versa. JSON has been used for over a decade to transmit objects from browser clients to servers over HTTP. Now, we can use it to serialize complex objects in and out of Web Storage in order to persist complex data types. Consider the script block in Listing 11-14.

Listing 11-14. JSON Object Storage

<script>

var data;

function loadData() {

data = JSON.parse(sessionStorage["myStorageKey"])

}

function saveData() {

sessionStorage["myStorageKey"] = JSON.stringify(data);

}

window.addEventListener("load", loadData, true); window.addEventListener("unload", saveData, true);

</script>

As you can see, the script contains event listeners to register handlers for load and unload events in the browser window. In this case, the handlers call the loadData() and saveData() functions, respectively.

In the loadData() function, the session storage area is queried for the value of a storage key, and that key is passed to the JSON.parse() function. The JSON.parse() routine will take a previously saved string representation of an object and reconstitute it into a copy of the original. This routine is called every time the page loads.

291

CHAPTER 11 USING THE STORAGE APIS

Similarly, the saveData() function takes a data value and calls JSON.stringify() on it to turn it into a string representation of the object. That string is, in turn, stored back into storage. By registering the saveData() function on the unload browser event, we ensure that it is called every time the user navigates away or shuts down the browser or window.

The practical result of these two functions is that any object we wish to track in storage, no matter if it is a complex object type, can be stored and reloaded as users navigate in and out of the application. This allows developers to extend the techniques we have already shown to nontext data.

A Window into Sharing

As alluded to in an earlier section, the ability for Web Storage events to fire in any window browsing the same origin has some powerful implications. It means that storage can be used to send messages from window to window, even if they are not all using the storage object itself. This, in turn implies that we can now share data across windows that have the same origin.

Let’s see how this works using some code samples. To listen to cross-window messages, a simple script needs only to register a handler for storage events. Let’s assume that a page running at http://www.example.com/storageLog.html contains the code shown in Listing 11-15 (the sample file storageLog.html for this example is also located in the code/storage folder).

Listing 11-15. Cross-Window Communication Using Storage

// display records of new storage events function displayStorageEvent(e) {

var incomingRow = document.createElement('div'); document.getElementById("container").appendChild(incomingRow);

var logged = "key:" + e.key + ", newValue:" + e.newValue + ", oldValue:" + e.oldValue + ", url:" + e.url + ", storageArea:" + e.storageArea; incomingRow.innerHTML = logged;

}

// add listeners on storage events window.addEventListener("storage", displayStorageEvent, true);

After registering an event listener for the storage event type, this window will receive notification of storage changes in any pages. For example, if a browser window viewing http://www.example.com/browser-test.html that is currently browsing the same origin sets or changes a new storage value, the storageLog.html page will receive a notification. Therefore, to send a message to a receiving window, the sending window need only modify a storage object, and its old and new values will be sent as part of the notification. For example, if a storage value is updated using localStorage.setItem(), then the displayStorageEvent() handler in the storageLog.html page hosted at the same origin will receive an event. By carefully coordinating event names and values, the two pages can now communicate, a feat which has been difficult to accomplish before. Figure 11-13 shows the storageLog.html page in action, simply logging storage events it receives.

292