ServiceWorkerGlobalScope: messageerror event
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.
Note: This feature is only available inService Workers.
Themessageerror event of theServiceWorkerGlobalScope interface occurs when incoming messages can't be deserialized.
This event is not cancelable and does not bubble.
In this article
Syntax
Use the event name in methods likeaddEventListener(), or set an event handler property.
addEventListener("messageerror", (event) => { })onmessageerror = (event) => { }Event type
AnExtendableMessageEvent. Inherits fromExtendableEvent.
Event properties
Inherits properties from its parent,ExtendableEvent.
ExtendableMessageEvent.dataRead onlyReturns the event's data. It can be any data type. If dispatched in
messageerrorevent, the property will benull.ExtendableMessageEvent.originRead onlyReturns the origin of the
Clientthat sent the message.ExtendableMessageEvent.lastEventIdRead onlyRepresents, inserver-sent events, the last event ID of the event source.
ExtendableMessageEvent.sourceRead onlyReturns a reference to the
Clientobject that sent the message.ExtendableMessageEvent.portsRead onlyReturns the array containing the
MessagePortobjects representing the ports of the associated message channel.
Examples
In the below example a page gets a handle to theServiceWorker object viaServiceWorkerRegistration.active, and then calls itspostMessage() function.
// main.jsif (navigator.serviceWorker) { navigator.serviceWorker.register("service-worker.js"); navigator.serviceWorker.addEventListener("message", (event) => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then((registration) => { registration.active.postMessage("Hi service worker"); });}The service worker can listen for the message deserialization error by listening to themessageerror event:
// service-worker.jsself.addEventListener("messageerror", (event) => { // event is an ExtendableMessageEvent object console.error("Message deserialization failed");});Alternatively, the script can listen for the message deserialization error usingonmessageerror:
// service-worker.jsself.onmessageerror = (event) => { // event is an ExtendableMessageEvent object console.error("Message deserialization failed");};Specifications
| Specification |
|---|
| Service Workers Nightly> # eventdef-serviceworkerglobalscope-messageerror> |
| Service Workers Nightly> # dom-serviceworkerglobalscope-onmessageerror> |