Who can hear this? A map of browser messaging

2025/08/02
browserweb-workerspostmessagemessagechannelfrontend

The browser gives you several ways to send a message. window.postMessage, worker.postMessage, MessageChannel, BroadcastChannel, a service worker talking to its pages. People trip on which one to reach for, but the syntax was never the hard part. The hard part is two questions you rarely ask out loud:

  1. Who actually receives this?
  2. Can I make it reach only them?

Each messaging API answers those two questions differently.

First trap: "postMessage" is not one method

postMessage is a name shared by several different methods, each living on a different object:

someWindow.postMessage(msg, targetOrigin)  // on a Window  (iframe, popup, parent, opener)
worker.postMessage(msg)                     // on a Worker
port.postMessage(msg)                       // on a MessagePort
client.postMessage(msg)                     // on a service worker Client

The tell is targetOrigin. Only the Window version takes one, because the window on the other end might be a different origin and the browser wants you to name who you trust. The worker and client versions have no targetOrigin because they are same-origin by nature (a Client is the service worker's handle to one of its pages). A port (one end of a MessageChannel) takes none either, because whoever created the channel already chose the recipient when handing over port2. From then on, a message sent from port1 reaches only port2, so there is no origin left to check.

The cast

Who can send and receive: a tab (window), an iframe or popup inside it, and the three workers. Each one runs its own JavaScript environment, and the rest of this article calls each of them a context.

  • Dedicated worker is a thread for one page, created with new Worker('a.js'). Besides pages, dedicated workers and shared workers can also call new Worker().
  • Shared worker is one worker shared by several tabs from the same origin. Even though every tab calls new SharedWorker('hub.js'), the browser starts only one hub.js. new SharedWorker() can only be called from a page, not from a worker.
  • Service worker sits between a set of pages and the network, like a proxy (offline, caching, push). It isn't created with new; a page calls navigator.serviceWorker.register('sw.js') to register it with the browser.

The default is louder than you think

You call postMessage on an iframe and assume you sent one message to one recipient:

iframe.contentWindow.postMessage('hello', 'https://trusted.com');

You didn't. You delivered it to the receiving window's message event, and every listener in that window gets a copy:

// anywhere in the receiving page, e.g. a third-party analytics script:
window.addEventListener('message', e => console.log('I got it too:', e.data));

Same origin does not mean "your code." An injected script, an ad SDK, a dependency that page loaded are all in the same context, all able to listen. BroadcastChannel is the same story on purpose: anyone who joins the channel name hears everything.

So broadcast is the default. The real question is how you opt out of it.

Private means handing over a port

The problem in the previous section is that the message travels on the message event, and anyone with a listener there receives it. To avoid it, use a line with only two ends: a MessageChannel.

For example, a page that wants a private line to the worker it created:

// the page's code
const worker = new Worker('worker.js');
const channel = new MessageChannel();            // one line, two ends: port1 and port2
worker.postMessage('setup', [channel.port2]);    // hand port2 to the worker
channel.port1.postMessage('only the worker hears this');
 
// worker.js
self.onmessage = (e) => {
  const port = e.ports[0];                       // port2, handed over by the page
  port.onmessage = (ev) => console.log(ev.data);
};

The second argument of worker.postMessage is the transfer list. Once port2 is handed over, the page no longer holds it; only the worker does. From then on, messages the page sends from port1 reach only port2 and never pass through any window's message event, so listeners other scripts attached on the page receive nothing.

The handover itself still travels on the message event. Because the port rides inside a postMessage, every message listener on the receiving side gets e.ports[0] and can attach its own listener to it. A worker usually runs only your own scripts, so other listeners rarely get the port. A page inside an iframe often loads third-party scripts such as ads and analytics, and they can get the port too.

From whom to whom

postMessage needs a handle to the other side before you can send. BroadcastChannel only needs both sides to open the same name. Here is each route, by where the message starts and where it ends:

  • page → iframe / popup: window.postMessage. The handle is iframe.contentWindow, or the return value of window.open(). Every listener on the receiving window hears it.
  • page ↔ dedicated worker: the page calls worker.postMessage, the worker calls self.postMessage. The handle is the return value of new Worker(). Only these two hear it.
  • page ↔ shared worker: both sides call port.postMessage. The page's port is new SharedWorker().port; the worker gets its port in onconnect. Each tab has its own port, and only the tab whose port the worker sends on hears it.
  • page → service worker: registration.active.postMessage. The registration comes from await navigator.serviceWorker.ready.
  • service worker → page: client.postMessage, one client per call. The client is e.source, or one of the results of clients.matchAll(). The page receives it on navigator.serviceWorker, not on window.
  • worker ↔ a dedicated worker it created: written the same way as page ↔ dedicated worker. Both dedicated and shared workers can call new Worker().
  • two workers, neither created by the other: for example two dedicated workers the same page created, a dedicated worker and a shared worker, or any worker and a service worker. Neither side holds a handle to the other, so the page creates a MessageChannel and gives one end to each, or they use BroadcastChannel.
  • unrelated same-origin tabs: BroadcastChannel. No handle needed; the same name is enough. Every context that opened that name hears it.

MessageChannel is not a separate route. It uses the postMessage of one of the routes above to hand a port over, and after that the two ends have a private line no one else receives. All three kinds of worker can call new MessageChannel() and new BroadcastChannel(), written the same way as in a page.

Three ways to send

postMessage — window to window (iframe, popup, opener)

There are three roles. A page on https://parent.example (call it parent) embeds an iframe from https://child.example and opens a popup to the same URL with window.open. Parent created both, so it holds their handles: the iframe's contentWindow and the return value of window.open. In the other direction, the iframe reaches parent through window.parent and the popup through window.opener.

The sender has to hold the other side's handle before it can send.

Right after parent embeds the iframe and opens the popup, their pages may not have loaded yet, and a message parent sends then never arrives. So below, the iframe and the popup each send ready once loaded, and parent replies by calling postMessage on e.source (the window that sent it).

// parent's page code (https://parent.example)
const popup = window.open('https://child.example');   // the popup parent opens
window.addEventListener('message', (e) => {
  if (e.origin !== 'https://child.example') return;
  console.log('parent got:', e.data);                 // 'iframe ready' or 'popup ready'
  e.source.postMessage('hi', 'https://child.example'); // e.source is the window that sent it
});
 
// code inside the iframe (https://child.example)
window.parent.postMessage('iframe ready', 'https://parent.example');
 
// code inside the popup (https://child.example)
window.opener.postMessage('popup ready', 'https://parent.example');

It can't reach an unrelated tab (you hold no handle to it). That is BroadcastChannel's job.

MessageChannel — a private 1:1 port between any two contexts

Picture one string with two tin cans (port1, port2). You call new MessageChannel(), keep one can, hand the other over; only the two holders hear it. A channel always has exactly these two cans. To connect a third party, create another MessageChannel.

The section "Private means handing over a port" showed a page running a line to its own worker. The same approach lets two workers talk directly. This example has three roles: the page, workerA and workerB. The page created both workers, so only the page holds handles to both; workerA and workerB have no handle to each other. The page creates one channel, gives port1 to workerA and port2 to workerB, and from then on the two workers talk directly, without the data passing through the page.

// the page's code
const workerA = new Worker('workerA.js');
const workerB = new Worker('workerB.js');
const ch = new MessageChannel();
workerA.postMessage('connect', [ch.port1]);
workerB.postMessage('connect', [ch.port2]);
 
// workerA.js (workerB.js is the mirror)
self.onmessage = (e) => {
  // e.ports is the list of ports attached to this message. The page attached only port1
  // for workerA, so [0] is port1; workerB uses the same line and gets port2
  const peer = e.ports[0];
  peer.onmessage = (ev) => console.log('A got from B:', ev.data);
  peer.postMessage('hi B, straight to you');   // never passes through the page
};

The page doing the matchmaking doesn't have to be the one that created the two workers; it only has to hold handles to both. For example, a tab connected to two shared workers, hub.js and hub2.js, can let the two hubs talk directly the same way; it just hands each port over through that hub's own .port.postMessage:

// a tab connected to both hubs
const hub1 = new SharedWorker('hub.js');
const hub2 = new SharedWorker('hub2.js');
const ch = new MessageChannel();
hub1.port.postMessage('peer', [ch.port1]);
hub2.port.postMessage('peer', [ch.port2]);
 
// hub.js (hub2.js is written the same way)
onconnect = (e) => {
  const tabPort = e.ports[0];            // the port this tab connected with
  tabPort.onmessage = (ev) => {
    if (ev.data !== 'peer') return;
    const peer = ev.ports[0];            // hub.js gets ch.port1, hub2.js gets ch.port2
    peer.onmessage = (m) => console.log('hub got:', m.data);
    peer.postMessage('hi from hub');     // goes straight to the other hub, not through the tab
  };
};
BroadcastChannel — broadcast to everyone on a name

There are four roles, all on the same origin:

  • tab1, tab2: two tabs open on the same site.
  • sw: the service worker that site registered, code in sw.js.
  • logout.js: a dedicated worker tab1 created with new Worker('logout.js').

They need no handles to each other. As long as each one calls new BroadcastChannel('app'), they are on the same channel.

// tab1's page code
const bc = new BroadcastChannel('app');
bc.onmessage = (e) => console.log('tab1 heard:', e.data);
const worker = new Worker('logout.js');
 
// tab2's page code (another tab on the same site)
const bc = new BroadcastChannel('app');
bc.onmessage = (e) => console.log('tab2 heard:', e.data);
 
// sw.js
const bc = new BroadcastChannel('app');
bc.onmessage = (e) => console.log('sw heard:', e.data);
 
// logout.js (the dedicated worker tab1 created) sends the message
const bc = new BroadcastChannel('app');
bc.postMessage({ type: 'logout' });

One postMessage from logout.js, and tab1, tab2 and sw all hear logout. The worker's own bc does not; a second new BroadcastChannel('app') inside that same worker would.

The browser stops a service worker that has been idle for a while; BroadcastChannel messages sent while it is stopped never reach it, not even after it starts again (measured in Chrome 153). For a message it must get, post from a page with (await navigator.serviceWorker.ready).active.postMessage(msg), which wakes it up.

The three workers

Dedicated worker — one page's own thread

Two roles: the page, and the worker it creates with new Worker('crunch.js'). The worker talks only to the page that created it; the page holds worker, and inside the worker, self replies to the page.

// the page's code
const worker = new Worker('crunch.js');
worker.postMessage({ rows: bigArray });
worker.onmessage = (e) => render(e.data);
 
// crunch.js (the worker)
self.onmessage = (e) => self.postMessage(heavyWork(e.data.rows));
Shared worker — many tabs, one worker

Say one site has three tabs open: tabA, tabB and tabC. Each tab's code calls new SharedWorker('hub.js'), the browser starts only one hub.js, and all three tabs connect to it. hub.js is the shared worker's own code.

Each time a tab connects, hub.js gets a new port object. A port carries no name or id, so hub.js cannot tell which tab it belongs to. In the code below, each tab reports its own id as soon as it connects, and hub.js stores the port in a Map under that id.

// tabA's page code (tabB and tabC are the same, with their own name instead of 'tabA')
const sw = new SharedWorker('hub.js');
sw.port.start();
sw.port.postMessage({ register: 'tabA' });
sw.port.onmessage = (e) => console.log('tabA got:', e.data);
 
// hub.js (the shared worker): one port per tab, kept by id
const tabs = new Map();
onconnect = (e) => {
  // the connect event's ports are not attached by the tab; the browser creates this one port
  // for the newly connected tab, so there is always exactly one
  const port = e.ports[0];
  port.onmessage = (ev) => { if (ev.data.register) tabs.set(ev.data.register, port); };
  port.start();
};
 
// once all three tabs have registered, hub.js calls these when it wants to send:
function sendToC() { tabs.get('tabC').postMessage('just for C'); }            // only tabC gets it
function sendToAll() { tabs.forEach((port) => port.postMessage('hi all')); } // tabA, tabB and tabC all get it
Service worker — a proxy between its pages and the network

Say one site has two tabs open, tabA and tabB, and the site's page registered a service worker with navigator.serviceWorker.register('sw.js'). Both tabs are controlled by the same sw.js, and to sw.js each one is a client. If tabA sends a message to sw.js first (code at the end of this section), sw.js can reply to tabA alone; sw.js can also send to tabA and tabB on its own, without waiting for either to send first.

// sw.js
self.addEventListener('message', (e) => {
  e.source.postMessage('reply, just to the tab that asked');  // only to the tab that sent the message, e.g. tabA
});
 
// proactive, no tab has to send first:
async function announce(msg) {
  const clients = await self.clients.matchAll({ type: 'window' });
  clients.forEach((c) => c.postMessage(msg));                 // tabA and tabB both get it
}

When tabA sends to sw.js first, or hands it a MessageChannel port, it calls postMessage on registration.active:

// tabA's page code
const reg = await navigator.serviceWorker.ready;
const ch = new MessageChannel();
reg.active.postMessage('line', [ch.port2]);
ch.port1.onmessage = (e) => console.log('from sw:', e.data);
 
// inside sw.js's message listener; tabA attached only ch.port2, so e.ports[0] is that port
e.ports[0]?.postMessage('reply on the private line');