HTML and CSS Reference
What about sending more than strings?
In the examples I've shown you so far, I've only passed strings
in messages back and forth. What about if you want to send
more than just a string? What if you have an object with proper-
ties and values?
Well, the good news is the specifi cation describes what's sup-
posed to happen when a browser has to safely send data from
one source to another. It describes how to clone the data and
how it should be treated.
However ... most browsers don't support this process. In fact,
most browsers simply coerce the object into a string. That sucks
for you and me. It means that instead of the nicely constructed
object, you'll get [object Object] in the event.data property.
In fact, we saw this before in Chapter 6, “Data Storage,” where
we try to store objects in localStorage . So in the same way
as we got around the issue with localStorage , you can use
pass it to postMessage and then, on the receiving side, convert
Using JSON.stringify and JSON.parse will be useful methods for
transferring more complicated objects from window to target, as
we'll see in the next sections on Web Workers and Web Sockets.
Web Workers are part of a separate specifi cation to the HTML5
spec, but are a key feature in building web applications.
background process to the main browser. This is effectively a
thread. What this means is the worker runs in the background
without interfering with the main browser thread.
The browser is already responsible for requesting and parsing
fi fi e s , r e n d e r fi n g t h e v fi e w , a n d e x e c u t fi n g J a v a S c r fi p t , a n d a n y t h fi n g
that consumes the browser's processing time causes all other
jobs to wait. This is where Web Workers come to the rescue.