Service worker communicate to clients
I don't believe that clients.fetchAll()
exists. You probably mean clients.matchAll()
, which should give you the behavior you describe:
self.clients.matchAll().then(clients => {
clients.forEach(client => client.postMessage({msg: 'Hello from SW'}));
})
A nicer alternative allowing the service worker to communicate with clients, while avoiding having to send messages one-by-one, is to make use of the Broadcast Channel API. It is now supported in recent versions of Chrome as well as in Firefox.
// From service-worker.js:
const channel = new BroadcastChannel('sw-messages');
channel.postMessage({title: 'Hello from SW'});
// From your client pages:
const channel = new BroadcastChannel('sw-messages');
channel.addEventListener('message', event => {
console.log('Received', event.data);
});
Adding includeUncontrolled
option should do:
for (const client of await clients.matchAll({includeUncontrolled: true, type: 'window'})) {
client.postMessage(message);
}