MessageChannel

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.

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

MessageChannelチャンネルメッセージング API のインターフェイスで、新しいメッセージチャンネルを作成し、2 つの MessagePort プロパティを通して、その間でデータを送信できます。

コンストラクター

MessageChannel()

2 つの新しい MessagePort オブジェクトを持つ新しい MessageChannel オブジェクトを返します。

プロパティ

MessageChannel.port1 読取専用

チャンネルの port1 を返します。

MessageChannel.port2 読取専用

チャンネルの port2 を返します。

次の例では、MessageChannel() コンストラクターを使用して新しいチャンネルを作成する様子を見ることができます。

iframe が読み込まれると、onmessage ハンドラーを MessageChannel.port1 に登録し、MessageChannel.port2window.postMessage メソッドを使用して iframe へ転送します。

IFrame からメッセージが返送されると、onMessage 関数はそのメッセージを段落に出力します。

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

// iframe が読み込まれるのを待つ
iframe.addEventListener("load", onLoad);

function onLoad() {
  // port1 のメッセージを待ち受けする
  channel.port1.onmessage = onMessage;

  // port2 を iframe へ転送する
  iframe.contentWindow.postMessage("メインページからこんにちは!", "*", [
    channel.port2,
  ]);
}

// port1 で受け取ったメッセージを処理する
function onMessage(e) {
  output.innerHTML = e.data;
}

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

仕様書

Specification
HTML
# message-channels

ブラウザーの互換性

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
MessageChannel
MessageChannel() constructor
port1
port2

Legend

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

Full support
Full support
Partial support
Partial support
Has more compatibility info.

関連情報