postMessage()
方法在
DedicatedWorkerGlobalScope
interface sends a message to the main thread that spawned it. This accepts a single parameter, which is the data to send to the worker. The data may be any value or JavaScript object handled by the
structured clone
algorithm, which includes cyclical references.
The main scope that spawned the worker can send back information to the thread that spawned it using the
Worker.postMessage
方法。
postMessage(aMessage, transferList);
Worker.onmessage
handler. This may be any value or JavaScript object handled by the
structured clone
algorithm, which includes cyclical references.
Transferable
objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (
neutered
) in the context it was sent from and it becomes available only to the main thread it was sent to.
MessagePort
and
ArrayBuffer
objects can be transferred.
Void.
The following code snippet shows
worker.js
, in which an
onmessage
handler is used to handle messages from the main script. Inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using
postMessage(workerResult);
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);
}
In the main script,
onmessage
would have to be called on a
Worker object
, 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 ).
注意
:
postMessage()
can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'DedicatedWorkerGlobalScope.postMessage()' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
postMessage
|
Chrome 4 | Edge 12 | Firefox 3.5 | IE 10 | Opera 10.6 | Safari 4 | WebView Android Yes | Chrome Android Yes | Firefox Android 4 | Opera Android 11 | Safari iOS 5.1 | Samsung Internet Android Yes |
完整支持
DedicatedWorkerGlobalScope
interface it belongs to.
DedicatedWorkerGlobalScope
close()
postMessage()