ServiceWorkerContainer: message event

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Note: This feature is available in Web Workers.

The message event is used in a page controlled by a service worker to receive messages from the service worker.

This event is not cancelable and does not bubble.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

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

onmessage = (event) => { }

Event type

A MessageEvent. Inherits from Event.

Event MessageEvent

Examples

In this example the service worker get the client's ID from a fetch event and then sends it a message using Client.postMessage:

js
// service-worker.js
async function messageClient(clientId) {
  const client = await clients.get(clientId);
  client.postMessage("Hi client!");
}

addEventListener("fetch", (event) => {
  messageClient(event.clientId);
  event.respondWith(() => {
    // …
  });
});

The client can receive the message by listening to the message event:

js
// main.js
navigator.serviceWorker.addEventListener("message", (message) => {
  console.log(message);
});

Alternatively, the client can receive the message with the onmessage event handler:

js
// main.js
navigator.serviceWorker.onmessage = (message) => {
  console.log(message);
};

Specifications

Specification
Service Workers Nightly
# dom-serviceworkercontainer-onmessage

Browser compatibility

See also