W3cubDocs

/Web APIs

MessagePort

The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.

MessagePort is a transferable object.

Note: This feature is available in Web Workers

EventTarget MessagePort

Instance methods

Inherits methods from its parent, EventTarget.

postMessage()

Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.

start()

Starts the sending of messages queued on the port (only needed when using EventTarget.addEventListener; it is implied when using onmessage).

close()

Disconnects the port, so it is no longer active.

Events

message

Fired when a MessagePort object receives a message.

messageerror

Fired when a MessagePort object receives a message that can't be deserialized.

Example

In the following example, you can see a new channel being created using the MessageChannel() constructor.

When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message.

When a message is received back from the IFrame, the onMessage function outputs the message to a paragraph.

js

const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");

// Wait for the iframe to load
iframe.addEventListener("load", onLoad);

function onLoad() {
  // Listen for messages on port1
  channel.port1.onmessage = onMessage;

  // Transfer port2 to the iframe
  iframe.contentWindow.postMessage("Hello from the main page!", "*", [
    channel.port2,
  ]);
}

// Handle messages received on port1
function onMessage(e) {
  output.innerHTML = e.data;
}

For a full working example, see our channel messaging basic demo on GitHub (run it live too).

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
MessagePort 2 12 41 10 10.6 5 4.4 18 41 11 4.2 1.0
close 2 12 41 10 10.6 5 4.4 18 41 11 4.2 1.0
message_event 2 12 41 10 10.6 5 ≤37 18 41 11.5 4.2 1.0
messageerror_event 60 18 57 No 47 16.4 60 60 57 47 16.4 8.0
postMessage 2 12 41 10 10.6 5 4.4 18 41 11 4.2 1.0
start 2 12 41 10 10.6 5 4.4 18 41 11 4.2 1.0
worker_support 4 12 41 10 ≤15 5 ≤37 18 41 ≤14 5 1.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/MessagePort