(updated ) by

Dedicated Worker Global Scope

With DedicatedWorkerGlobalScope it gives you direct interaction with both sides of worker/main thread.

main.js

const worker = new Worker("/worker.js");
worker.postMessage("hello from main");

// now we can listen for messages from the DedicatedWorkerGlobalScope

// note we are adding the event listener to the worker
worker.addEventListener("message", (e) => {
  console.log("message from worker", e.data);
});

worker.js

onmessage = (e) => {
  console.log("message from main", e.data);
  // note we are using self here
  self.postMessage("hello from worker");
};