blob: 1ead51bd873cf7fe13245135b5d703ff8dd36393 (
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
|
---
title: 'Worker: message event'
slug: Web/API/Worker/message_event
translation_of: Web/API/Worker/message_event
---
<div>{{APIRef}}</div>
<div>当 worker 的父级接收到来自其 worker 的消息时,会在 {{domxref('Worker')}} 对象上触发 <code>message</code> 事件。例如:当 worker 通过 <code><a href="/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage">DedicatedWorkerGlobalScope.postMessage()</a></code> 发送了一条消息时。</div>
<table class="properties">
<tbody>
<tr>
<th scope="row">是否冒泡</th>
<td>否</td>
</tr>
<tr>
<th scope="row">是否可撤销</th>
<td>否</td>
</tr>
<tr>
<th scope="row">接口</th>
<td>{{domxref("MessageEvent")}}</td>
</tr>
<tr>
<th scope="row">对应事件处理属性</th>
<td><code><a href="/en-US/docs/Web/API/Worker/onmessage">onmessage</a></code></td>
</tr>
</tbody>
</table>
<h2 id="例子">例子</h2>
<p>下面的代码创建了一个 worker 并使用 <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code> 监听从 worker 发来的消息:</p>
<pre class="brush: js">const worker = new Worker("static/scripts/worker.js");
worker.addEventListener('message', (event) => {
console.log(`Received message from worker: ${event.data}`)
});</pre>
<p>另外,也可以使用 <code><a href="/en-US/docs/Web/API/Worker/onmessage">onmessage</a></code> 事件处理属性进行监听:</p>
<pre class="brush: js">const worker = new Worker("static/scripts/worker.js");
worker.onmessage = (event) => {
console.log(`Received message from worker: ${event.data}`)
};</pre>
<p>worker 使用 <code><a href="/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage">self.postMessage()</a></code> 发出消息:</p>
<pre class="brush: js">// static/scripts/worker.js
self.postMessage('I\'m alive!');</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
</tr>
<tr>
<td>{{SpecName('HTML WHATWG', 'indices.html#event-message')}}</td>
<td>{{Spec2('HTML WHATWG')}}</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("api.Worker.message_event")}}</p>
<h2 id="另请参阅">另请参阅</h2>
<ul>
<li>相关事件: <code><a href="/docs/Web/API/Worker/messageerror_event">messageerror</a></code>.</li>
<li><code><a href="/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage">DedicatedWorkerGlobalScope.postMessage()</a></code>.</li>
</ul>
|