Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Worker
  4. postMessage()

Worker: postMessage() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Note: This feature is available inWeb Workers, except forService Workers.

ThepostMessage() method of theWorker interface sends a message to the worker. The first parameter is the data to send to the worker. The data may be any JavaScript object that can be handled by thestructured clone algorithm.

TheWorkerpostMessage() method delegates to theMessagePortpostMessage() method, which adds a task on the event loop corresponding to the receivingMessagePort.

TheWorker can send back information to the thread that spawned it using theDedicatedWorkerGlobalScope.postMessage method.

Syntax

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

Parameters

message

The object to deliver to the worker; this will be in thedata field in the event delivered to themessage event. This may be any value or JavaScript object handled by thestructured clone algorithm, which includes cyclical references.

Themessage parameter is mandatory. If the data to be passed to the worker is unimportant,null orundefined must be passed explicitly.

transferOptional

An optionalarray oftransferable objects to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. These transferable objects should be attached to the message; otherwise they would be moved but not actually accessible on the receiving end.

optionsOptional

An optional object containing the following properties:

transferOptional

Has the same meaning as thetransfer parameter.

Return value

None (undefined).

Examples

The following code snippet shows the creation of aWorker object using theWorker() constructor. When either of two form inputs (first andsecond) have their values changed,change events invokepostMessage() to send the value of both inputs to the current worker.

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

For a full example, see oursimple worker example (run example).

Note:postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

Transfer Example

This minimum example hasmain create anArrayBuffer and transfer it tomyWorker, then hasmyWorker transfer it back tomain, with the size logged at each step.

main.js code

js
// create workerconst myWorker = new Worker("myWorker.js");// listen for myWorker to transfer the buffer back to mainmyWorker.addEventListener("message", (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 bufferconst myBuf = new ArrayBuffer(8);console.log(  "buf.byteLength in main BEFORE transfer to worker:",  myBuf.byteLength,);// send myBuf to myWorker and transfer the underlying ArrayBuffermyWorker.postMessage(myBuf, [myBuf]);console.log(  "buf.byteLength in main AFTER transfer to worker:",  myBuf.byteLength,);

myWorker.js code

js
// listen for main to transfer the buffer to myWorkerself.onmessage = (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,  );};

Output logged

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

byteLength goes to 0 after theArrayBuffer is transferred. For a more sophisticated full working example ofArrayBuffer transfer, see this Firefox demo add-on:GitHub :: ChromeWorker - demo-transfer-arraybuffer

Specifications

Specification
HTML
# dom-worker-postmessage-dev

Browser compatibility

See also

  • TheWorker interface it belongs to.

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp