DedicatedWorkerGlobalScope.onmessage - Web APIs 编辑
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
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.
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:
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 |
---|---|---|
HTML Living Standard The definition of 'DedicatedWorkerGlobalScope.onmessage' in that specification. | Living Standard |
Browser compatibility
BCD tables only load in the browser
See also
- The
DedicatedWorkerGlobalScope
interface it belongs to. WorkerGlobalScope
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论