diff options
Diffstat (limited to 'files/zh-cn/web/api/messagechannel/index.html')
-rw-r--r-- | files/zh-cn/web/api/messagechannel/index.html | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/files/zh-cn/web/api/messagechannel/index.html b/files/zh-cn/web/api/messagechannel/index.html new file mode 100644 index 0000000000..47cb52146f --- /dev/null +++ b/files/zh-cn/web/api/messagechannel/index.html @@ -0,0 +1,87 @@ +--- +title: MessageChannel +slug: Web/API/MessageChannel +tags: + - API + - Channel Messaging API + - Interface + - MessageChannel + - Reference + - web messaging +translation_of: Web/API/MessageChannel +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>Channel Messaging API的<strong><code>MessageChannel</code></strong> 接口允许我们创建一个新的消息通道,并通过它的两个{{domxref("MessagePort")}} 属性发送数据。</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="属性">属性</h2> + +<dl> + <dt>{{domxref("MessageChannel.port1")}} {{readonlyInline}}</dt> + <dd>返回channel的port1。</dd> + <dt>{{domxref("MessageChannel.port2")}} {{readonlyInline}}</dt> + <dd>返回channel的port2。</dd> +</dl> + +<h2 id="构造函数">构造函数</h2> + +<dl> + <dt>{{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}</dt> + <dd> + <p>返回一个带有两个MessagePort属性的MessageChannel新对象。</p> + </dd> +</dl> + +<h2 id="示例">示例</h2> + +<p>在以下代码块中,您可以看到使用MessageChannel构造函数实例化了一个channel对象。当iframe加载完毕,我们使用MessagePort.postMessage方法把一条消息和MessageChannel.port2传递给iframe。handleMessage处理程序将会从iframe中(使用MessagePort.onmessage监听事件)接收到信息,将数据其放入innerHTML中。</p> + +<pre class="brush: js">var channel = new MessageChannel(); +var para = document.querySelector('p'); + +var ifr = document.querySelector('iframe'); +var otherWindow = ifr.contentWindow; + +ifr.addEventListener("load", iframeLoaded, false); + +function iframeLoaded() { + otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); +} + +channel.port1.onmessage = handleMessage; +function handleMessage(e) { + para.innerHTML = e.data; +} </pre> + +<p>一个完整的运行示例,可以在Github上查看 <a class="external external-icon" href="https://github.com/mdn/dom-examples/tree/master/channel-messaging-basic">channel messaging basic demo</a> (<a class="external external-icon" href="https://mdn.github.io/dom-examples/channel-messaging-basic/">run it live too</a>).</p> + +<h2 id="Specifications规范">Specifications/规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#message-channels','MessageChannel')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No difference from {{SpecName("HTML5 Web Messaging")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{Compat("api.MessageChannel")}}</div> + +<div id="compat-mobile"></div> + +<h2 id="参见">参见</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Channel_Messaging_API/Using_channel_messaging">Using channel messaging</a></li> +</ul> |