Glossary / Message channels
Message channels
A MessageChannel creates two entangled MessagePort objects that can exchange messages. It provides an explicit, independently addressable communication path between windows, workers, frames, or components, and ports can be transferred to another execution context.
Ports and lifecycle
const channel = new MessageChannel();
channel.port1.onmessage = ({ data }) => console.log(data);
worker.postMessage({ port: channel.port2 }, [channel.port2]);
The second port is transferred as a transferable, so ownership moves to the receiver; the sender should no longer use that transferred port. A receiver can attach onmessage or call addEventListener("message", handler) and start() when using event listeners in contexts where explicit start is required. port.close() releases the endpoint. Ports may be used to establish a private request/reply channel instead of routing all messages through a global worker message handler.
Messages follow structured-clone rules. Cloneable data is copied; transferable objects such as ArrayBuffer can move ownership; shared memory remains shared under its security and runtime rules. Functions, DOM nodes, and many host objects cannot be cloned. Treat inbound messages as untrusted data and validate shape, size, and permitted operations.
Patterns and tradeoffs
A dedicated channel is useful for isolating a protocol, handing a capability to a component, or connecting two contexts that do not otherwise have a direct reference. It does not guarantee delivery after a context closes, provide persistence, or define application-level correlation, timeouts, retries, or backpressure. Define message types and versioning, request identifiers, error replies, and shutdown behavior. Bound queues at the application layer if producers can outrun consumers.
Ports are capabilities: possession gives the holder the ability to communicate through that endpoint. Avoid transferring a port to untrusted code unless that authority is intended. A port can be passed through another context, so ownership and revocation matter.
Interview questions
- What does
MessageChannelcreate? Two entangled ports that can send messages to one another. - Why transfer
port2to a worker? Transfer moves that endpoint's ownership so the worker can use it as its own communication capability. - Does a channel provide durable delivery or retries? No; those are application protocol concerns.
- How does its payload behave? It follows structured-clone and transferable rules.
- When is it preferable to a worker's global
messageevent? When a private or separately scoped communication path makes ownership and protocol boundaries clearer.