通道消息 API
允许 2 个单独脚本在附加到同一文档的不同浏览上下文中运行 (如:2 个 IFrame、或主文档和 IFrame,2 个文档凭借
SharedWorker
,或 2 个工作者) 通过 2 端带有端口的双向通道 (或管道) 在彼此之间直接通信,传递消息。
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
MessagePort
s; an experimental solution to allow broadcasting of a message to multiple ports simultaneously.
<iframe>
.
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'Channel messaging' in that specification. |
实时标准 |
MessageChannel
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持