Movatterモバイル変換


[0]ホーム

URL:


  1. 開発者向けのウェブ技術
  2. Web API
  3. MessageChannel

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。

View in EnglishAlways switch to English

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 プロパティを通して、その間でデータを送信できます。

コンストラクター

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

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp