MDN self-hosted library · e01.org

Worker: message event

Web Workers APIwindowandworkerexceptservice

Web Workers APIwindow_and_worker_except_service

The message event is fired on a Worker object when the worker's parent receives a message from its worker (i.e., when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()).

This event is not cancellable and does not bubble.

Syntax

Use the event name in addEventListener():

addEventListener("message", (event) => { })

Alternatively, assign to the event handler property of the interface:

onmessage = (event) => { }

Event type

A MessageEvent. Inherits from Event.

MessageEvent

Examples

This code creates a new worker and listens to messages from it using addEventListener():

const worker = new Worker("static/scripts/worker.js");

worker.addEventListener("message", (event) => {
  console.log(`Received message from worker: ${event.data}`);
});

Alternatively, it could listen using the onmessage event handler property (but note that this replaces other event listeners added using onmessage, if any):

const worker = new Worker("static/scripts/worker.js");

worker.onmessage = (event) => {
  console.log(`Received message from worker: ${event.data}`);
};

The worker posts messages using self.postMessage():

// static/scripts/worker.js

self.postMessage("I'm alive!");

Specifications

Browser compatibility

See also