aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/messagechannel/index.html
blob: 47cb52146faf732c6f605f82d35aca3b4f85c69d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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>