Reference

SharedWorker

One process, many same-origin contexts. Normative: WHATWG Web workers.

Construct (each tab/window)

const worker = new SharedWorker("shared.js");
// optional name to distinguish instances:
// new SharedWorker("shared.js", "session-bus");

// Communicate via explicit port (not worker.onmessage)
worker.port.onmessage = (e) => { /* … */ };
worker.port.postMessage({ type: "hello" });

// If using addEventListener for "message", call start():
// worker.port.start();

Inside the shared worker

// SharedWorkerGlobalScope
onconnect = (e) => {
  const port = e.ports[0];

  port.onmessage = (ev) => {
    // handle; reply on this port only, or fan-out to all ports you stored
    port.postMessage({ type: "ack", echo: ev.data });
  };
  // port.start() if you used addEventListener instead of onmessage
};

Rules that matter

vs alternatives

Need Prefer
Offload CPU for one page Dedicated Worker
Pub/sub between tabs only BroadcastChannel (lighter; no shared process)
One shared in-memory coordinator SharedWorker (ports + fan-out you implement)
Offline / network proxy Service Worker

Debug