MessageChannel: port2 プロパティ

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.

メモ: この機能はウェブワーカー内で利用可能です。

port2MessageChannel インターフェイスの読み取り専用プロパティで、メッセージチャンネルの第 2 ポートを返します。このポートは、チャンネルのもう一方の端のコンテキストに接続されたポートで、メッセージが最初に送信される先です。

チャンネルの第 2 ポートを表す MessagePort オブジェクト。これはチャネルのもう一方の端のコンテキストに接続されたポートです。

次のコードブロックでは、 MessageChannel() コンストラクターを使用して作成された新しいチャンネルが見られます。iframe が読み込まれると、port2 を iframe へ、メッセージを通して MessagePort.postMessage を使用して渡します。すると、 handleMessage ハンドラーが <iframe> から返送されたメッセージに(MessagePort.message_event を使用して)返答し、これを段落に挿入します。 メッセージが到着したタイミングを調べるために、port1 が待ち受けされています。

js
const channel = new MessageChannel();
const para = document.querySelector("p");

const ifr = document.querySelector("iframe");
const otherWindow = ifr.contentWindow;

ifr.addEventListener("load", iframeLoaded, false);

function iframeLoaded() {
  otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]);
}

channel.port1.onmessage = handleMessage;
function handleMessage(e) {
  para.innerHTML = e.data;
}

完全に動作する例は、Github 上の channel messaging basic demo を参照してください (実際のデモも実行できます)。

仕様書

Specification
HTML
# dom-messagechannel-port2-dev

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
port2

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報