DedicatedWorkerGlobalScope: 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 only available inDedicated Web Workers.
ThepostMessage() method of theDedicatedWorkerGlobalScope interface sends a message to the main thread that spawned it.
This accepts a data parameter, which contains data to copy from the worker to the main thread.The data may be any value or JavaScript object handled by thestructured clone algorithm, which includes cyclical references.
The method also accepts an optional array oftransferable objects totransfer to the main thread;Unlike the data parameter transferred objects are no longer usable in the worker thread.(Where possible, objects are transferred using a high performance zero-copy operation).
The main scope that spawned the worker can send back information to the thread that spawned it using theWorker.postMessage method.
In this article
Syntax
postMessage(message)postMessage(message, transfer)postMessage(message, options)Parameters
messageThe object to deliver to the main thread; this will be in the data field in the event delivered to the
messageevent.This may be any value or JavaScript object handled by thestructured clone algorithm, which includes cyclical references.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 showsworker.js, in which anonmessage 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 usingpostMessage(workerResult);
onmessage = (e) => { console.log("Message received from main script"); const 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 aWorker object, whereas inside the worker script you just needonmessage because the worker is effectively the global scope (DedicatedWorkerGlobalScope).
For a full example, see ourBasic dedicated worker example (run dedicated worker).
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.
Specifications
| Specification |
|---|
| HTML> # dom-dedicatedworkerglobalscope-postmessage-dev> |
Browser compatibility
See also
TheDedicatedWorkerGlobalScope interface it belongs to.