The preceding example created a web worker, which indeed ran in its own thread. But, this is not very helpful to us because we need to be able to communicate with the workers that we create. In this section, we'll cover the basic mechanisms involved with sending and receiving messages from web workers, including how these messages are serialized.
When we want to pass data into a web worker, we use the postMessage()
method. As the name suggests, this method posts the given message to the worker. If there are any message event handlers set up within the worker, they'll respond to this call. Let's look at a basic example that sends a string to a worker:
// Launches the worker thread. var worker = new Worker('worker.js'); // Posts a message to the worker, triggering // any "message" event handlers. worker.postMessage('hello world');
Now let's look at the worker that responds to this message by setting up an event handler for the message event:
// Setup...