Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting messages from a service worker to a client page

Today we can find many examples of sending message from a service worker to a client, but always following the reception of a message event in the service worker.

I would like to know if we can send messages independently of this event? And if yes, how? I tried few things, without success...

In my case, it's for redirect a client to a new page when my service worker receives a push event.

like image 367
Mathieu Le Bihan Avatar asked Dec 03 '25 23:12

Mathieu Le Bihan


2 Answers

client.js :

const swListener = new BroadcastChannel('swListener');
swListener.onmessage = function(e) {
  console.log('swListener Received', e.data);
};

service-worker.js

  const swListener = new BroadcastChannel('swListener');
   swListener.postMessage('This is From SW');
like image 191
Haytham Tomeh Avatar answered Dec 06 '25 13:12

Haytham Tomeh


The interface for Client.postMessage() is described at https://github.com/slightlyoff/ServiceWorker/issues/609. Unfortunately, it is not fully implemented in Google Chrome as of version 45, though I'd expect it to make it into a version at a later date.

When the functionality's available, you could use self.clients.matchAll() to obtain a list of any open pages that are being controlled by the service worker, and call the postMessage() method on the specific client that you care about. You need to keep in mind that it's entirely possible that there won't be any tabs open with a page controlled by your service worker, in which case you'd want to do something like open a new client page with your target URL.

But, there's a method that's probably more appropriate for your use case (though also not currently support in Chrome 45): WindowClient.navigate(), which will instruct an open tab controlled by your service worker to navigate to a different URL on the same origin.

like image 22
Jeff Posnick Avatar answered Dec 06 '25 11:12

Jeff Posnick