The onmessage
property of the Worker
interface represents an EventHandler
, that is a function to be called when the message
event occurs. These events are of type MessageEvent
and will be called when the worker's parent receives a message (i.e. from the DedicatedWorkerGlobalScope.postMessage
method).
Note: The message payload is available in the message
event's data
property.
Syntax
myWorker.onmessage = function(e) { ... }
Example
The following code snippet shows creation of a Worker
object using the Worker()
constructor. Messages are passed to the worker when the value inside the form input first
changes. An onmessage handler is also present, to deal with messages that are passed back from the worker.
var myWorker = new Worker('worker.js');
first.onchange = function() {
myWorker.postMessage([first.value,second.value]);
console.log('Message posted to worker');
}
myWorker.onmessage = function(e) {
result.textContent = e.data;
console.log('Message received from worker');
}
In the worker.js
script, an onmessage
handler is used to the handle messages from the main script:
onmessage = function(e) {
console.log('Message received from main script');
var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
console.log('Posting message back to main script');
postMessage(workerResult);
}
Notice how in the main script, onmessage
has to be called on myWorker
, whereas inside the worker script you just need onmessage
because the worker is effectively the global scope (DedicatedWorkerGlobalScope
).
For a full example, see ourBasic dedicated worker example ([[../../../../../../../mdn.github.io/simple-web-worker/index|run dedicated worker]]).
Specifications
Specification | Status | Comment |
HTML Living StandardThe definition of 'Worker.onmessage' in that specification. | Living Standard |
Browser compatibility
The compatibility table in 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.
Update compatibility data on GitHub
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
onmessage
|
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 |
Safari iOS
Full support 5.1 |
Samsung Internet Android
Full support 1.0 |
Legend
- Full support
- Full support
See also
The Worker
interface it belongs to.
Worker.onmessage by Mozilla Contributors is licensed under CC-BY-SA 2.5.