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

CHAPTER 11 USING THE STORAGE APIS

Local Versus Session Storage

Sometimes, an application needs values that persist beyond the life of a single tab or window or need to be shared across multiple views. In these cases, it is more appropriate to use a different Web Storage implementation: localStorage. The good news is that you already know how to use localStorage. The only programmatic difference between sessionStorage and localStorage is the name by which each is accessed—through the sessionStorage and localStorage objects, respectively. The primary behavioral differences are how long the values persist and how they are shared. Table 11-1 shows the differences between the two types of storage.

Table 11-1. Differences Between sessionStorage and localStorage

sessionStorage

localStorage

Values persist only as long as the window or tab

Values persist beyond window and browser lifetimes.

in which they were stored (survives a browser

 

refresh; not a browser restart).

 

Values are only visible within the window or tab that created them.

Values are shared across every window or tab running at the same origin.

Keep in mind that browsers sometimes redefine the lifespan of a tab or window. For example, some browsers will save and restore the current session when a browser crashes, or when a user shuts down the display with many open tabs. In these cases, the browser may choose to keep the sessionStorage around when the browser restarts or resumes. So, in effect, sessionStorage may live longer than you think!

Other Web Storage API Attributes and Functions

The Web Storage API is one of the simplest in the HTML5 set. We have already looked at both explicit and implicit ways to set and retrieve data from the session and local storage areas. Let’s complete our survey of the API by looking at the full set of available attributes and function calls.

The sessionStorage and localStorage objects can be retrieved from the window object of the document in which they are being used. Other than their names and the duration of their values, they are identical in functionality. Both implement the Storage interface, which is shown in Listing 11-2.

Listing 11-2. The Storage Interface

interface Storage {

readonly attribute unsigned long length; getter DOMString key(in unsigned long index); getter any getItem(in DOMString key);

setter creator void setItem(in DOMString key, in any data); deleter void removeItem(in DOMString key);

void clear();

};

Let’s look at the attributes and functions here in more detail.

269

CHAPTER 11 USING THE STORAGE APIS

The length attribute specifies how many key-value pairs are currently stored in the storage object. Remember that storage objects are specific to their origin, so that implies that the items (and length) of the storage object only reflect the items stored for the current origin.

The key(index) function allows retrieval of a given key. Generally, this is most useful when you wish to iterate across all the keys in a particular storage object. Keys are zero-based, meaning that the first key is at index (0) and the last key is at index (length – 1). Once a key is retrieved, it can be used to fetch its corresponding value. Keys will retain their indices over the life of a given storage object unless a key or one of its predecessors is removed.

As you’ve already seen, getItem(key) function is one way to retrieve the value based on a given key. The other is to reference the key as an array index to the storage object. In both cases, the value null will be returned if the key does not exist in storage.

Similarly, setItem(key, value) function will put a value into storage under the specified key name, or replace an existing value if one already exists under that key name. Note that it is possible to receive an error when setting an item value; if the user has storage turned off for that site, or if the storage is already filled to its maximum amount, a QUOTA_EXCEEDED_ERR error will be thrown during the attempt. Make sure to handle such an error should your application depend on proper storage behavior.

Figure 11-3. Quota Exceeded Error in Chrome

270

CHAPTER 11 USING THE STORAGE APIS

The removeItem(key) function does exactly as you might expect. If a value is currently in storage under the specified key, this call will remove it. If no item was stored under that key, no action is taken.

Note Unlike some collection and data frameworks, removing an item does not return the old value as a result of the call to remove it. Make sure you’ve stored any copy you need independent of the removal.

Finally, the clear() function removes all values from the storage list. It is safe to call this on an empty storage object; as such, a call will simply do nothing.

DISK SPACE QUOTA

Peter says: “The specification recommends that browsers allow five megabytes per origin. Browsers should prompt the user when the quota is reached in order to grant more space and may also provide ways for users to see how much space each origin is using.

In reality, the behavior is still a bit inconsistent. Some browsers silently allow a larger quota or prompt for a space increase, while others simply throw the QUOTA_EXCEEDED_ERR error shown in Figure 11-3, while others, like Opera, shown in Figure 11-4, implement a nice way to allocate more quota on the fly. The test file testQuota.html used in this example is located in the code/storage directory.”

Figure 11-4. On-the-fly Quota increase in Opera

271

CHAPTER 11 USING THE STORAGE APIS

Communicating Web Storage Updates

Sometimes, things get a little more complicated, and storage needs to be accessed by more than one page, browser tab, or worker. Perhaps your application needs to trigger many operations in succession whenever a storage value is changed. For just these cases, the Web Storage API includes an event mechanism to allow notifications of data updates to be communicated to interested listeners. Web Storage events are fired on the window object for every window of the same origin as the storage operation, regardless of whether or not the listening window is doing any storage operations itself.

Note Web Storage events can be used to communicate between windows on the same origin. This will be explored a bit more thoroughly in the “Practical Extras” section.

To register to receive the storage events of a window’s origin, simply register an event listener, for example:

window.addEventListener("storage", displayStorageEvent, true);

As you can see, the name storage is used to indicate interest in storage events. Any time a Storage event—either sessionStorage or localStorage—for that origin is raised any registered event listener will receive the storage event as the specified event handler. The storage event itself takes the form shown in Listing 11-3.

Listing 11-3. The StorageEvent Interface

interface StorageEvent : Event { readonly attribute DOMString key; readonly attribute any oldValue; readonly attribute any newValue; readonly attribute DOMString url;

readonly attribute Storage storageArea;

};

The StorageEvent object will be the first object passed to the event handler, and it contains all the information necessary to understand the nature of the storage change.

The key attribute contains the key value that was updated or removed in the storage.

The oldValue contains the previous value corresponding to the key before it was updated, and the newValue contains the value after the change. If the value was newly added, the oldValue will be null, and if the value has been removed, the newValue will be null.

The url will point to the origin where the storage event occurred.

Finally, the storageArea provides a convenient reference to the sessionStorage or localStorage where the value was changed. This gives the handler an easy way to query the storage for current values or make changes based on other storage changes.

272