Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Worker.onmessage

この記事はまだボランティアによって 日本語 に翻訳されていません。ぜひ MDN に参加して翻訳を手伝ってください!

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 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 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 (run dedicated worker).

Specifications

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

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 4 3.5 10.0 10.6 4
Feature Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support 4.4 3.5 1.0.1 10.0 11.5 5.1

See also

The Worker interface it belongs to.

ドキュメントのタグと貢献者

 このページの貢献者: teoli, chrisdavidmills, kscarfone
 最終更新者: teoli,