Worker: message event
The message
event is fired on a Worker
object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()
).
Bubbles | No |
---|---|
Cancelable | No |
Interface | MessageEvent |
Event handler property | onmessage |
Examples
This code creates a new worker and listens to messages from it using addEventListener()
:
const worker = new Worker("static/scripts/worker.js"); worker.addEventListener('message', (event) => { console.log(`Received message from worker: ${event.data}`) });
Alternatively, it could listen using the onmessage
event handler property:
const worker = new Worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`Received message from worker: ${event.data}`) };
The worker posts messages using self.postMessage()
:
// static/scripts/worker.js self.postMessage('I\'m alive!');
Specifications
Specification |
---|
HTML Standard (HTML) # event-message |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
message_event |
4 |
12 |
3.5 |
10 |
10.6 |
4 |
4 |
18 |
4 |
11.5 |
5 |
1.0 |
See also
- Related events:
messageerror
. -
DedicatedWorkerGlobalScope.postMessage()
.
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event