Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DedicatedWorkerGlobalScope.postMessage() — sending messages from a worker

DedicatedWorkerGlobalScope.postMessage sends data from a dedicated worker to its creator. The recipient reads it through event.data. The method supports structured cloning and optional transfer of object ownership.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

self.postMessage(message)
self.postMessage(message, transfer)
self.postMessage(message, { transfer })

DedicatedWorkerGlobalScope.postMessage is a Web API method available inside a dedicated worker as self.postMessage(). It sends a message to its creator; the recipient handles the message event on the Worker object and reads event.data. Worker.postMessage() operates in the opposite direction.

The message argument holds one value; package multiple items in an object or array. Structured cloning also supports circular references. The optional transfer array, supplied directly or as { transfer }, transfers ownership of supported objects instead of copying them. They can no longer be used on the sending side. The list alone does not include objects in the message: they must be contained in it or otherwise accessible to the recipient.

The method returns undefined, not the recipient's response. This is a browser API, not an ECMAScript feature; MDN marks it as widely available. The example creates a dedicated worker, sends 21, and logs the response 42.

Examples

const source = `
self.onmessage = (event) => {
  self.postMessage(event.data * 2);
};
`;
const url = URL.createObjectURL(
  new Blob([source], { type: "text/javascript" })
);
const worker = new Worker(url);

worker.onmessage = (event) => {
  console.log(event.data);
  worker.terminate();
  URL.revokeObjectURL(url);
};
worker.onerror = () => {
  worker.terminate();
  URL.revokeObjectURL(url);
  console.error("Worker failed");
};
worker.postMessage(21);

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources