Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

MessageChannel — communication through paired ports

MessageChannel creates two connected ports for asynchronous, bidirectional messaging. Learn how to receive events, start delivery, clone data, and close ports when communication is finished.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const channel = new MessageChannel();
channel.port2.onmessage = (event) => {
  /* event.data */
  channel.port1.close();
  channel.port2.close();
};
// With addEventListener('message', handler), call port.start().
channel.port1.postMessage(value);

new MessageChannel() creates two connected MessagePort objects, exposed through the read-only properties port1 and port2. A message sent through one port reaches the other as a message event; read its payload from event.data. Delivery is asynchronous and does not interrupt the current task.

Assigning onmessage automatically starts the port's receiving queue. With addEventListener('message', handler), call start() on the receiving port. The example logs sent first, then received: hello; after receiving the message, it closes both ports with close().

postMessage() uses structured cloning rather than sharing ordinary objects. Uncloneable data causes DataCloneError. An optional transfer list transfers supported objects instead of copying them; a MessagePort itself can be transferred to another window or worker.

This is a Web API defined by HTML, not a feature of a particular ECMAScript edition. The constructor is exposed in Window and Worker contexts and supported by current browser engines. Having Node 24 in a repository does not establish support in the target browser.

Examples

(() => {
  const channel = new MessageChannel();

  channel.port2.addEventListener('message', (event) => {
    console.log(`received: ${event.data.text}`);
    channel.port1.close();
    channel.port2.close();
  }, { once: true });
  channel.port2.start();

  channel.port1.postMessage({ text: 'hello' });
  console.log('sent');
})();

Result

sent
received: hello

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources