Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Worker: handling `message`, `error`, and `messageerror`

Tell apart three dedicated worker events: successful message delivery, a worker error, and a message the receiver cannot deserialize.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const worker = new Worker(url);
worker.onmessage = (event) => { /* use event.data */ };
worker.onerror = (event) => { /* handle a worker error */ };
worker.onmessageerror = (event) => { /* handle a receive-side deserialization failure */ };

// Alternative for any of the three properties:
worker.addEventListener("message", handleMessage);
worker.addEventListener("error", handleError);
worker.addEventListener("messageerror", handleMessageError);

Worker.onmessage/onerror/onmessageerror refers to three event handler properties on the dedicated Worker instance, on the side that created it. They are defined by HTML, not ECMAScript 2024. Runtime support varies, especially for messageerror. Install the handlers before sending the first request.

worker.onmessage receives a MessageEvent when a message from the worker is successfully deserialized. Read the payload from event.data and check that it has the shape your application expects: structured cloning does not validate your protocol. Inside the worker, self.onmessage handles the opposite direction, receiving messages from the creator.

worker.onerror receives one event object. An uncaught synchronous exception reported to the creator produces an ErrorEvent; do not rely on event.error carrying the original exception. A script load failure can produce a plain Event. For a cancelable event, event.preventDefault() can stop further reporting, but it does not resume the interrupted code. Inside the worker, self.onerror has a legacy five-argument form for ErrorEvent and can cancel reporting with return true; that rule does not apply to worker.onerror.

worker.onmessageerror receives a non-cancelable MessageEvent instead of message when the receiver cannot deserialize a message. There is no decoded payload to read. By contrast, passing a function to postMessage() throws DataCloneError synchronously on the sending side; it does not produce a messageerror on the receiving side.

Each property holds one handler: assigning a new one replaces it, and assigning null clears it. Use addEventListener() with the event name without on to register independent listeners. Call worker.terminate() when you no longer need the worker; it does not wait for pending work to finish.

Examples

(() => {
  const inNode = typeof require === "function" &&
    typeof process !== "undefined" && Boolean(process.versions?.node);

  const handler = `
    function handleMessage(data, reply) {
      if (data === "fail") throw new Error("demo failure");
      reply(data * 2);
    }
  `;

  let worker;
  let messageErrorTarget;

  function reportMessageError(event) {
    console.log(event.isTrusted ? "messageerror" : "messageerror (synthetic)");
  }

  function receiveReply(data) {
    console.log(`message: ${data}`);
    messageErrorTarget.dispatchEvent(new MessageEvent("messageerror"));
    worker.postMessage("fail");
  }

  if (inNode) {
    const { Worker: ThreadWorker } = require("node:worker_threads");
    worker = new ThreadWorker(handler + `
      const { parentPort } = require("node:worker_threads");
      parentPort.on("message", (data) => {
        handleMessage(data, (value) => parentPort.postMessage(value));
      });
    `, { eval: true });

    // Node worker threads do not use the browser's handler properties.
    messageErrorTarget = new EventTarget();
    messageErrorTarget.addEventListener("messageerror", reportMessageError);
    worker.on("message", receiveReply);
    worker.on("error", (error) => {
      if (error.message !== "demo failure") throw error;
      console.log("error: runtime");
    });
  } else {
    const script = handler + `
      self.onmessage = ({ data }) => {
        handleMessage(data, (value) => self.postMessage(value));
      };
    `;
    const url = URL.createObjectURL(new Blob([script], { type: "text/javascript" }));
    try {
      worker = new Worker(url);
    } catch (error) {
      URL.revokeObjectURL(url);
      throw error;
    }

    messageErrorTarget = worker;
    worker.onmessage = (event) => receiveReply(event.data);
    worker.onmessageerror = reportMessageError;
    worker.onerror = (event) => {
      event.preventDefault();
      console.log(event instanceof ErrorEvent ? "error: runtime" : "error: startup");
      worker.terminate();
      URL.revokeObjectURL(url);
    };
  }

  try {
    worker.postMessage(() => {});
  } catch (error) {
    console.log(`send: ${error.name}`);
  }
  worker.postMessage(21);
})();

Result

send: DataCloneError
message: 42
messageerror (synthetic)
error: runtime

To try the Web Worker handler properties, run the full snippet in a browser console on a page whose security policy permits `blob:` workers. For Node.js 24, save it as `main.cjs` and run `node main.cjs`; that path uses `node:worker_threads`, not the browser's `Worker` handler properties. In both environments, `messageerror (synthetic)` tests only the handler, not a real deserialization failure or native event support.

Related lessons

  • JavaScript · Lesson 32 · Advanced · Version: 4

Sources