DedicatedWorkerGlobalScope.onmessage

Summary

The onmessage property of the DedicatedWorkerGlobalScope interface represents an EventHandler to be called when the message event occurs and bubbles through the Worker — i.e. when a message is sent to the worker using the Worker.postMessage method.

Syntax

JavaScript
self.onmessage = function() { ... };

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. A Worker.onmessage handler is also present, to deal with messages are passed back from the worker.

JavaScript
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, a DedicatedWorkerGlobalScope.onmessage handler is used to handle messages from the main script:

JavaScript
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 (the DedicatedWorkerGlobalScope, in this case).

For a full example, see ourBasic dedicated worker example (run dedicated worker).

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'DedicatedWorkerGlobalScope.onmessage' in that specification.
Living Standard No change from Web Workers.
Web Workers
The definition of 'DedicatedWorkerGlobalScope.onmessage' in that specification.
Candidate Recommendation Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 4 3.5 (1.9.1) 10 10.6 4
Feature Android Chrome for Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? (Yes) 1.0 (1.9.1) 1.0.1 10 11.5 5.1

See also

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/dedicatedworkerglobalscope/onmessage

API DedicatedWorkerGlobalScope onmessage Property Reference Référence Web Workers