JavaScript Workers Communicating with a Web Worker

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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"
}


Got any JavaScript Question?