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 | Status |
|---|---|
| HTML Living Standard | Living Standard |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
message event | Chrome Full support 4 | Edge Full support 12 | Firefox Full support 3.5 | IE Full support 10 | Opera Full support 10.6 | Safari Full support 4 | WebView Android Full support 4 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 11.5 | Safari iOS Full support 5.1 | Samsung Internet Android Full support 1.0 |
Legend
- Full support
- Full support
See also
- Related events:
messageerror. DedicatedWorkerGlobalScope.postMessage().
