MessageChannel: port1 プロパティ

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.

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

port1MessageChannel インターフェイスの読み取り専用プロパティで、メッセージチャンネルの第 1 ポートを返します。このポートは、チャンネルの元となるコンテキストに付属します。

チャンネルの第 1 ポートを表す MessagePort オブジェクト。これはチャンネルの元となるコンテキストに付属するポートです。

次のコードブロックでは、 MessageChannel() コンストラクターを使用して作成された新しいチャンネルが見られます。 <iframe> が読み込まれると、 MessageChannel.port2<iframe> へ、メッセージを通して MessagePort.postMessage を使用して渡します。すると、 handleMessage ハンドラーが <iframe> から返送されたメッセージに(MessagePort.message_event を使用して)返答し、これを段落に挿入します。メッセージが到着したとき、 handleMessage メソッドが 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;
}

仕様書

Specification
HTML
# dom-messagechannel-port1-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
port1

Legend

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

Full support
Full support

関連情報