MessageChannel, MessagePort, and MessageEvent provide same-realm
messaging. This surface does not create a worker boundary.
MessageChannel and MessagePort
const channel = new MessageChannel();
channel.port2.onmessage = (event) => {
console.log(event.data);
};
channel.port1.postMessage({ hello: "world" });
// handler runs synchronouslyA channel creates two entangled ports. MessagePort cannot be constructed
directly.
postMessage(value, transfer?)sends a copied value to the partner.- Messages buffer until the receiving port starts.
- Assigning
onmessagestarts the port. start()drains buffered messages.close()detaches the pair and drops queued messages.onmessage,onmessageerror, andoncloseare available.
Clone behavior
Primitive values, arrays, plain objects, cycles, Date, RegExp, Map,
Set, and ArrayBuffer values are copied while retaining their JavaScript
types and contents. Functions reject immediately with DataCloneError.
MessageEvent
MessageEvent extends Event and exposes data, origin,
lastEventId, source, and ports. The legacy
initMessageEvent() method is also available.
For worker lifecycle limitations, see node:worker_threads.