Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. MessagePort

MessagePort

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨September 2015⁩.

Note: This feature is available inWeb Workers.

TheMessagePort interface of theChannel Messaging API represents one of the two ports of aMessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.

MessagePort is atransferable object.

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 usingEventTarget.addEventListener; it is implied when usingonmessage).

close()

Disconnects the port, so it is no longer active.

Events

Inherits events from its parent,EventTarget.

message

Fired when aMessagePort object receives a message.

messageerror

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

Example

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

When the IFrame has loaded, we register anonmessage handler forMessageChannel.port1 and transferMessageChannel.port2 to the IFrame using thewindow.postMessage method along with a message.

When a message is received back from the IFrame, theonMessage 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 loadiframe.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 port1function onMessage(e) {  output.innerHTML = e.data;}

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

Specifications

Specification
HTML
# message-ports

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp