How to send a message from service worker to a Workbox class instance's "message" event?
Asked Answered
S

1

6

I have this in my window.js...

const wb = new Workbox('sw.js');

wb.messageSW({type:'START'});

wb.addEventListener('message', e=>{
   console.log(e);
});

...in my sw.js, I have...

self.addEventListener('message', (e)=>{
   if (e.data) {
       switch(e.data.type) {
           case 'START':
               //do some processing here...
               //...then how do I send a message to the client here so...
               //...that it will be received by the wb.addEventListener('message',... in window.js?
           break;
       }
   }
});

I tried sending via the MessagePort.postMessage() in e.ports[0] but it did not work. I feel this is something basic especially with the use of the Workbox class but I just can't get it to work.

My last resort is to use BroadcastChannel (with the polyfill) but I'm trying this one first as it may not need any polyfill for it to work.

Siesta answered 22/9, 2019 at 17:20 Comment(0)
W
7

You should be able to use the following to send a message from the service worker to all WindowClients (i.e. one or more instances of your web app, open in potentially multiple tabs):

const clients = await self.clients.matchAll({type: 'window'});
for (const client of clients) {
  client.postMessage({...});
}

That call to client.postMessage({...}) should trigger the handler in your web app that was registered via wb.addEventListener('message', ...).

Waisted answered 23/9, 2019 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.