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.
In this article
Syntax
postMessage(message)postMessage(message, transfer)postMessage(message, options)Parameters
messageThe object to deliver to the worker; this will be in the
datafield in the event delivered to themessageevent. This may be any value or JavaScript object handled by thestructured clone algorithm, which includes cyclical references.The
messageparameter is mandatory. If the data to be passed to the worker is unimportant,nullorundefinedmust be passed explicitly.transferOptionalAn 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.
optionsOptionalAn optional object containing the following properties:
transferOptionalHas the same meaning as the
transferparameter.
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.
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
// 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
// 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
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:10byteLength 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
- The
Workerinterface it belongs to.