通道消息 API

通道消息 API 允许 2 个单独脚本在附加到同一文档的不同浏览上下文中运行 (如:2 个 IFrame、或主文档和 IFrame,2 个文档凭借 SharedWorker ,或 2 个工作者) 通过 2 端带有端口的双向通道 (或管道) 在彼此之间直接通信,传递消息。

注意: 此特征可用于 Web 工作者 .

通道消息概念和用法

A message channel is created using the MessageChannel() constructor. Once created, the two ports of the channel can be accessed through the MessageChannel.port1 and MessageChannel.port2 properties (which both return MessagePort objects.) The app that created the channel uses port1 , and the app at the other end of the port uses port2 — you send a message to port2 , and transfer the port over to the other browsing context using window.postMessage along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.)

When these transferable objects are transferred, they are 'neutered' on the previous context — the one they previously belonged to. For instance a port, when is sent, cannot be used anymore by the original context.

The other browsing context can listen for the message using MessagePort.onmessage , and grab the contents of the message using the event's data attribute. You could then respond by sending a message back to the original document using MessagePort.postMessage .

When you want to stop sending messages down the channel, you can invoke MessagePort.close to close the ports.

Find out more about how to use this API in Using channel messaging .

通道消息接口

MessageChannel
Creates a new message channel to send messages across.
MessagePort
Controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other.
PortCollection
An array of MessagePort s; an experimental solution to allow broadcasting of a message to multiple ports simultaneously.

范例

规范

规范 状态 Comment
HTML Living Standard
The definition of 'Channel messaging' in that specification.
实时标准

浏览器兼容性

MessageChannel

更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
MessageChannel Chrome 4 Edge 12 Firefox 41 IE 10 Opera 10.6 Safari 5 WebView Android 4.4 Chrome Android 18 Firefox Android 41 Opera Android 11 Safari iOS 5.1 Samsung Internet Android 1.0

图例

完整支持
完整支持

MessagePort

更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
MessagePort Chrome 4 Edge 12 Firefox Yes IE 10 Opera 10.6 Safari 5 WebView Android Yes Chrome Android 18 Firefox Android Yes Opera Android 11 Safari iOS 5.1 Samsung Internet Android 1.0

图例

完整支持

另请参阅