CKTIS / JavaScript
Worker events: messages and errors
Worker.onmessage receives worker replies, Worker.onerror reports worker failures, and Worker.onmessageerror handles unsuccessful deserialization of an incoming message. These three handlers belong to the Worker object in the code that created the worker.
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
worker.onmessage = (event) => { /* event.data */ };
worker.onerror = (event) => { /* worker failure */ };
worker.onmessageerror = (event) => { /* deserialization failure */ };Worker.onmessage, Worker.onerror, and Worker.onmessageerror name properties assigned on an instance, such as worker.onmessage. They handle the message, error, and messageerror events respectively on the creator side of a dedicated worker. These are Web APIs specified by HTML, not features of a particular ECMAScript edition.
Worker.onmessage receives a MessageEvent; the transmitted value is in event.data. Calling worker.postMessage(value) sends data into the worker, while self.postMessage(value) inside the worker sends a reply. Worker.onerror, in contrast, receives one event argument reporting a worker failure. Do not confuse it with self.onerror inside the worker, which has a historical multi-argument signature.
Worker.onmessageerror receives a MessageEvent when an incoming message cannot be deserialized. It is not a general computation-error handler or a replacement for handling exceptions on the sending side. Data passed to postMessage() must be supported by the structured clone algorithm. Neither message nor messageerror bubbles or can be canceled.
Alternatives are addEventListener("message", handler), addEventListener("error", handler), and addEventListener("messageerror", handler). MDN marks message and error as widely available but messageerror as having limited availability; check your target browsers. Having Node 24 in a repository does not establish browser support for these APIs.
Examples
(() => {
const source = 'self.onmessage = (event) => { self.postMessage(event.data * 2); };';
const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
let worker;
const cleanup = () => {
worker?.terminate();
URL.revokeObjectURL(url);
};
try {
worker = new Worker(url);
worker.onmessage = (event) => {
console.log(`result: ${event.data}`);
cleanup();
};
worker.onerror = () => {
console.error('worker error');
cleanup();
};
worker.onmessageerror = () => {
console.error('message deserialization error');
cleanup();
};
worker.postMessage(21);
} catch (error) {
cleanup();
throw error;
}
})();Result
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.