Mathieu Le Bihan
Mathieu Le Bihan

Reputation: 53

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.

Upvotes: 3

Views: 3566

Answers (2)

Haytham Tomeh
Haytham Tomeh

Reputation: 177

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');

Upvotes: 9

Jeff Posnick
Jeff Posnick

Reputation: 56044

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.

Upvotes: 1

Related Questions