Back to Content

MessagePort

files/en-us/web/api/messageport/index.md

latest2.8 KB
Original Source

{{APIRef("Channel Messaging API")}} {{AvailableInWorkers}}

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

MessagePort is a transferable object.

{{InheritanceDiagram}}

Instance methods

Inherits methods from its parent, {{domxref("EventTarget")}}.

  • {{domxref("MessagePort.postMessage","postMessage()")}}
    • : Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
  • {{domxref("MessagePort.start","start()")}}
    • : Starts the sending of messages queued on the port (only needed when using {{domxref("EventTarget.addEventListener")}}; it is implied when using {{domxref("MessagePort.message_event", "onmessage")}}).
  • {{domxref("MessagePort.close","close()")}}
    • : Disconnects the port, so it is no longer active.

Events

Inherits events from its parent, {{domxref("EventTarget")}}.

  • {{domxref("MessagePort.message_event","message")}}
    • : Fired when a MessagePort object receives a message.
  • {{domxref("MessagePort.messageerror_event","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 {{domxref("MessageChannel.MessageChannel","MessageChannel()")}} constructor.

When the IFrame has loaded, we register an {{domxref("MessagePort/message_event","onmessage")}} handler for {{domxref("MessageChannel.port1")}} and transfer {{domxref("MessageChannel.port2")}} to the IFrame using the {{domxref("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

{{Specifications}}

Browser compatibility

{{Compat}}

See also