HTML and CSS Reference
In-Depth Information
means that if you have several pop-ups or several iframes, all
those documents can access this single shared worker and this
single shared worker will serve all those documents.
This would be useful, for example, for applications like Gmail or
Facebook, where client-side data needs to be maintained, such
as messages for the user, and you have several different win-
dows open.
The worker can access and manage the website's client-side Web
SQL Databases and IndexedDB (both discussed in Chapter 6).
It can also maintain the connection with the server, handling
all the data that's coming in and out—perhaps even via a Web-
Socket to the server, as we'll see in the next chapter—so that
data is handled in real time. The shared worker can then main-
tain all the changes to the client-side messages database and
push all those updates via postMessage to each of the pop-ups,
iframes, and so on.
This means that there's no chance of data getting out of sync—
or chance of race conditions if each of the pop-ups, iframes,
and so on was individually connecting to the server and trying
to each manage the client side—since the shared worker is the
single point of contact for all of that type of work.
The SharedWorker works slightly differently when it comes to
communication. For starters there's the concept of ports—this
is an array-like object that contains a reference to each of the
communication channels the shared worker has. Also, if you
bind to the message event using addEventListener , you have
to manually start the worker, which I'll show you in the following
code sample.
In addition, within the worker the connect event fires when the
SharedWorker is created, which can be used to keep track of
how many connections the worker has to other documents.
The documents creating the SharedWorker contain the
following code:
var worker = new SharedWorker('messages.js');
worker.port.addEventListener('message', function(event) {
var messages = JSON.parse(;
}, false);
Search WWH ::

Custom Search