Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

566 CHAPTER 15 Local data with web storage


before that entry was updated in browser tab two. In this scenario, tab one doesn’t know that
the value it displayed has just become stale.
To solve this problem, web storage has a storage event that is raised whenever an entry is
added, updated, or removed. You can subscribe to this event within your application to pro-
vide notification when something has changed and inform you of specific details about those
changes. These events work in both localStorage and sessionStorage.

After this lesson, you will be able to:
■■Understand the StorageEvent object.
■■Implement the event handling on the localStorage object.

Estimated lesson time: 20 minutes

Sending notifications only to other windows


The W3C recommends that events not be received in the tab (or window) that made the
change when working with storage events. This makes sense because the intent is to allow
other windows to respond when a storage value changes. However, some browsers (such as
later versions of Internet Explorer) have implemented storage events in a way that allows the
source window to receive the notification, too. It is only safe to rely on this implementation if
your application will target those browsers specifically.

Using the StorageEvent object reference


Subscribers to the storage event receive a StorageEvent object containing detailed infor-
mation about what has changed. The following is a list of properties included on the
StorageEvent object.
■■key Gets the key of the record that was added, updated, or removed; will be null or
empty if the event was triggered by the clear() method
■■oldValue Gets the initial value if the entry was updated or removed; will be null or
empty if a new item was added or the clear() method was invoked
■■newValue Gets the new value for new and updated entries; will be null or empty if
the event was triggered by either the removeItem() or clear() methods
■■url Gets the URL of the page on which the storage action was made
■■storageArea Gets a reference to either the window’s localStorage or sessionStorage
object, depending on which was changed
Many browsers initially began supporting storage events without fully implementing the
properties of the StorageEvent interface specification, so some older browsers might trigger
storage events, but the properties outlined here might be null or empty.
Free download pdf