MessageChannel - Web APIs 编辑

The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties.

Note:

This feature is available in Web Workers.

Properties

MessageChannel.port1 Read only
Returns port1 of the channel.
MessageChannel.port2 Read only
Returns port2 of the channel.

Constructor

MessageChannel()

Returns a new MessageChannel object with two new MessagePort objects.

Example

In the following example, you can see a new channel being created using the MessageChannel.MessageChannel constructor.

When the IFrame has loaded, we register an onmessage handler for  MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message.

When a message is received back from the IFrame, the onMessage function outputs the message to a paragraph.

var channel = new MessageChannel();
var output = document.querySelector('.output');
var iframe = document.querySelector('iframe');

// Wait for the iframe to load
iframe.addEventListener("load", onLoad);

function onLoad() {
  // Listen for messages on port1
  channel.port1.onmessage = onMessage;

  // Transfer port2 to the iframe
  iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
}

// Handle messages received on port1
function onMessage(e) {
  output.innerHTML = e.data;
}

For a full working example, see our channel messaging basic demo on Github (run it live too).

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'Message channels' in that specification.
Living Standard 

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:117 次

字数:3945

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文