HTML and CSS Reference
In-Depth Information
At this point, you'd be forgiven for thinking that you can call
methods inside the worker from your document, and that data
can be returned from the worker to your document. Poppycock!
No, in fact, to work with a worker, everything must be communi-
cated through posting messages between the worker and your
document. It's like some scene from Romeo and Juliet, exchang-
ing letters of love between the browser and the worker.
The only way you get can information to the worker is via
postMessage :
worker.postMessage('hello worker!');
Note that the postMessage in the Web Workers, unlike postMessage
in the Messaging API, only requires a single argument. The
only way you can receive information from the worker is via the
onmessage event handler:
worker.onmessage = function (event) {
alert('The worker just sent me this: ' + event.data);
};
Yo u s h o u l d n o w b e r e c o g n i s i n g t h e postMessage/onmessage
combination from the Messaging API from earlier in this chapter.
Yo u r e m e m b e r h o w w e c a in o in l y s e in d a in d r e c e i v e s t r i in g s i in t h e
Messaging API? You won't be surprised to know, then, that the
Web Workers have the same constraint.
Equally, the code inside the worker must also communicate
using the postMessage / onmessage combo. However, a Web
Worker doesn't have the same access as your normal docu-
ment: It's very much sandboxed and has access to only a select
few APIs and functions, as I'll show you in the next section.
The only other method available to you via the worker object
is terminate , which does exactly what it says on the tin. The
worker ceases to run and the worker object becomes limp and
useless. In particular, you can't resume the worker; you'd have
to create a brand new one.
What you can do inside a worker
Within a Web Worker you don't have access to such pleasures as
the DOM. In fact, if you need to do anything with the DOM, you're
going to have to prepare the work in the worker, and then pass it
to the parent document to do the actual DOM manipulation.
 
Search WWH ::




Custom Search