The ExtendableMessageEvent interface of the Service Worker API represents the event object of a message event fired on a service worker (when a message is received on the ServiceWorkerGlobalScope from another context) — extends the lifetime of such events.
// in the page being controlledif(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 receive the message by listening to the message event:
js
// in the service workeraddEventListener("message",(event)=>{// event is an ExtendableMessageEvent object
console.log(`The client sent me a message: ${event.data}`);
event.source.postMessage("Hi client");});