onmessage
特性为
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
方法。
self.onmessage = function() { ... };
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. A
Worker.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');
}
在
worker.js
script, a
DedicatedWorkerGlobalScope.onmessage
handler is used to 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 (the
DedicatedWorkerGlobalScope
, in this case).
For a full example, see our Basic dedicated worker example ( run dedicated worker ).
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'DedicatedWorkerGlobalScope.onmessage' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
onmessage
|
Chrome 4 | Edge 12 | Firefox 3.5 | IE 10 | Opera 10.6 | Safari 4 | WebView Android 37 | Chrome Android Yes | Firefox Android 4 | Opera Android 11 | Safari iOS 5.1 | Samsung Internet Android Yes |
完整支持
DedicatedWorkerGlobalScope
interface it belongs to.
WorkerGlobalScope
DedicatedWorkerGlobalScope
名称
onmessage
onmessageerror