Worker: postMessage() 方法

注意: 此功能在 Web Workers 中可用,但 Service Workers 除外。

postMessage() 方法是 Worker 接口的方法,用于向 worker 发送消息。第一个参数是要发送给 worker 的数据。数据可以是任何可由 结构化克隆算法 处理的 JavaScript 对象。

WorkerpostMessage() 方法委托给 MessagePortpostMessage() 方法,该方法在与接收 MessagePort 对应的事件循环中添加一个任务。

Worker 可以使用 DedicatedWorkerGlobalScope.postMessage 方法将信息发送回生成它的线程。

语法

js
postMessage(message)
postMessage(message, transfer)
postMessage(message, options)

参数

message

要传递给 worker 的对象;这将位于传递给 message 事件的 data 字段中。这可以是任何值或 JavaScript 对象,由 结构化克隆 算法处理,包括循环引用。

message 参数是必需的。如果要传递给 worker 的数据不重要,则必须显式传递 nullundefined

transfer 可选

一个可选的 数组,其中包含要转移所有权的 可转移对象。这些对象的拥有权将被授予目标端,并且在发送端不再可用。这些可转移对象应该附加到消息;否则,它们将被移动,但实际上无法在接收端访问。

options 可选

一个包含以下属性的可选对象

transfer 可选

transfer 参数具有相同的含义。

返回值

无 (undefined).

示例

以下代码段演示了使用 Worker() 构造函数创建 Worker 对象。当两个表单输入(firstsecond)中的任何一个的值发生变化时,change 事件会调用 postMessage(),将两个输入的值发送给当前 worker。

js
const myWorker = new Worker("worker.js");

first.onchange = () => {
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

second.onchange = () => {
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

有关完整的示例,请参阅我们的 简单 worker 示例 (运行示例).

注意: postMessage() 只能一次发送单个对象。如上所示,如果要传递多个值,可以发送一个数组。

传输示例

此最小示例具有 main 创建 ArrayBuffer 并将其传输到 myWorker,然后让 myWorker 将其传输回 main,并在每个步骤中记录大小。

main.js 代码

js
// create worker
const myWorker = new Worker("myWorker.js");

// listen for myWorker to transfer the buffer back to main
myWorker.addEventListener("message", function handleMessageFromWorker(msg) {
  console.log("message from worker received in main:", msg);

  const bufTransferredBackFromWorker = msg.data;

  console.log(
    "buf.byteLength in main AFTER transfer back from worker:",
    bufTransferredBackFromWorker.byteLength,
  );
});

// create the buffer
const myBuf = new ArrayBuffer(8);

console.log(
  "buf.byteLength in main BEFORE transfer to worker:",
  myBuf.byteLength,
);

// send myBuf to myWorker and transfer the underlying ArrayBuffer
myWorker.postMessage(myBuf, [myBuf]);

console.log(
  "buf.byteLength in main AFTER transfer to worker:",
  myBuf.byteLength,
);

myWorker.js 代码

js
// listen for main to transfer the buffer to myWorker
self.onmessage = function handleMessageFromMain(msg) {
  console.log("message from main received in worker:", msg);

  const bufTransferredFromMain = msg.data;

  console.log(
    "buf.byteLength in worker BEFORE transfer back to main:",
    bufTransferredFromMain.byteLength,
  );

  // send buf back to main and transfer the underlying ArrayBuffer
  self.postMessage(bufTransferredFromMain, [bufTransferredFromMain]);

  console.log(
    "buf.byteLength in worker AFTER transfer back to main:",
    bufTransferredFromMain.byteLength,
  );
};

输出日志

bash
buf.byteLength in main BEFORE transfer to worker:        8                     main.js:19
buf.byteLength in main AFTER transfer to worker:         0                     main.js:27

message from main received in worker:                    MessageEvent { ... }  myWorker.js:3
buf.byteLength in worker BEFORE transfer back to main:   8                     myWorker.js:7
buf.byteLength in worker AFTER transfer back to main:    0                     myWorker.js:15

message from worker received in main:                    MessageEvent { ... }  main.js:6
buf.byteLength in main AFTER transfer back from worker:  8                     main.js:10

byteLengthArrayBuffer 被传输后变为 0。有关 ArrayBuffer 传输更复杂的完整工作示例,请参阅此 Firefox 演示附加组件:GitHub :: ChromeWorker - demo-transfer-arraybuffer

规范

规范
HTML 标准
# dom-worker-postmessage-dev

浏览器兼容性

BCD 表格仅在浏览器中加载

另请参阅

  • 它所属的 Worker 接口。