--- title: 'Worker: message event' slug: Web/API/Worker/message_event translation_of: Web/API/Worker/message_event ---
message
事件。例如:当 worker 通过 DedicatedWorkerGlobalScope.postMessage()
发送了一条消息时。是否冒泡 | 否 |
---|---|
是否可撤销 | 否 |
接口 | {{domxref("MessageEvent")}} |
对应事件处理属性 | onmessage |
下面的代码创建了一个 worker 并使用 addEventListener()
监听从 worker 发来的消息:
const worker = new Worker("static/scripts/worker.js"); worker.addEventListener('message', (event) => { console.log(`Received message from worker: ${event.data}`) });
另外,也可以使用 onmessage
事件处理属性进行监听:
const worker = new Worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`Received message from worker: ${event.data}`) };
worker 使用 self.postMessage()
发出消息:
// static/scripts/worker.js self.postMessage('I\'m alive!');
Specification | Status |
---|---|
{{SpecName('HTML WHATWG', 'indices.html#event-message')}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.Worker.message_event")}}