JavaScript Communicating with a Web Worker


Example

Since workers run in a separate thread from the one that created them, communication needs to happen via postMessage.

Note: Because of the different export prefixes, some browsers have webkitPostMessage instead of postMessage. You should override postMessage to make sure workers "work" (no pun intended) in the most places possible:

worker.postMessage = (worker.webkitPostMessage || worker.postMessage);

From the main thread (parent window):

// Create a worker
var webworker = new Worker("./path/to/webworker.js");

// Send information to worker
webworker.postMessage("Sample message");

// Listen for messages from the worker
webworker.addEventListener("message", function(event) {
    // `event.data` contains the value or object sent from the worker
    console.log("Message from worker:", event.data); // ["foo", "bar", "baz"]
});

From the worker, in webworker.js:

// Send information to the main thread (parent window)
self.postMessage(["foo", "bar", "baz"]);

// Listen for messages from the main thread
self.addEventListener("message", function(event) {
    // `event.data` contains the value or object sent from main
    console.log("Message from parent:", event.data); // "Sample message"
});

Alternatively, you can also add event listeners using onmessage:

From the main thread (parent window):

webworker.onmessage = function(event) {
    console.log("Message from worker:", event.data); // ["foo", "bar", "baz"]
}

From the worker, in webworker.js:

self.onmessage = function(event) {
    console.log("Message from parent:", event.data); // "Sample message"
}