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);
					

参数

aMessage
The object to deliver to the main thread; this will be in the data field in the event delivered to the Worker.onmessage handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
transferList 可选
An optional array of 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.
实时标准

浏览器兼容性

The compatibility table on 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
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.

元数据

  • 最后修改: