Worker: message event

当 worker 的父级接收到来自其 worker 的消息时,会在 Worker 对象上触发 message 事件。例如:当 worker 通过 DedicatedWorkerGlobalScope.postMessage() 发送了一条消息时。
是否冒泡
是否可撤销
接口 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
HTML Living Standard Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
message eventChrome Full support 4Edge Full support 12Firefox Full support 3.5IE Full support 10Opera Full support 10.6Safari Full support 4WebView Android Full support 4Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11.5Safari iOS Full support 5.1Samsung Internet Android Full support Yes

Legend

Full support  
Full support

另请参阅