Mathieu Le Bihan Mathieu Le Bihan - 3 years ago 144
Javascript Question

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

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

Answer Source

The interface for Client.postMessage() is described at 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download