onmessage 特性为 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 方法)。

注意 : The message payload is available in the message event's data 特性。

句法

myWorker.onmessage = function(e) { ... }
					

范例

The following code snippet shows creation of a Worker 对象使用 Worker() constructor. Messages are passed to the worker when the value inside the form input 第一 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');
}
					

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

规范

规范 状态 注释
HTML 实时标准
The definition of 'Worker.onmessage' in that specification.
实时标准

浏览器兼容性

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. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
onmessage Chrome 4 Edge 12 Firefox 3.5 IE 10 Opera 10.6 Safari 4 WebView Android 4 Chrome Android 18 Firefox Android 4 Opera Android 11 Safari iOS 5.1 Samsung Internet Android 1.0

图例

完整支持

完整支持

另请参阅

Worker interface it belongs to.

元数据

  • 最后修改: