このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
MessageChannel
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年9月.
メモ: この機能はウェブワーカー内で利用可能です。
MessageChannel はチャンネルメッセージング API のインターフェイスで、新しいメッセージチャンネルを作成し、2 つのMessagePort プロパティを通して、その間でデータを送信できます。
In this article
コンストラクター
MessageChannel()2 つの新しい
MessagePortオブジェクトを持つ新しいMessageChannelオブジェクトを返します。
プロパティ
MessageChannel.port1読取専用チャンネルの port1 を返します。
MessageChannel.port2読取専用チャンネルの port2 を返します。
例
次の例では、MessageChannel() コンストラクターを使用して新しいチャンネルを作成する様子を見ることができます。
iframe が読み込まれると、onmessage ハンドラーをMessageChannel.port1 に登録し、MessageChannel.port2 をwindow.postMessage メソッドを使用して iframe へ転送します。
IFrame からメッセージが返送されると、onMessage 関数はそのメッセージを段落に出力します。
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> |