ServiceWorkerContainer: messageerror event

Baseline 2023

Newly available

Since March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

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

The messageerror event is fired to the ServiceWorkerContainer when an incoming message sent to the associated worker can't be deserialized.

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("messageerror", (event) => {});

onmessageerror = (event) => {};

Event type

Event properties

This interface also inherits properties from its parent, Event.

MessageEvent.data Read only

The data sent by the message emitter.

MessageEvent.origin Read only

A string representing the origin of the message emitter.

MessageEvent.lastEventId Read only

A string representing a unique ID for the event.

MessageEvent.source Read only

A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.

MessageEvent.ports Read only

An array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

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 self.clients.get(clientId);
  client.postMessage("Hi client!");
}

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

The service worker can listen for the message deserialization error by listening to the messageerror event:

js
// main.js
navigator.serviceWorker.addEventListener("messageerror", (event) => {
  console.error("Receive message from service worker failed!");
});

Alternatively, the script can listen for the message deserialization error using onmessageerror:

js
// main.js
navigator.serviceWorker.onmessageerror = (event) => {
  console.error("Receive message from service worker failed!");
};

Specifications

Specification
Service Workers
# dom-serviceworkerglobalscope-onmessageerror

Browser compatibility

BCD tables only load in the browser

See also