Reputation: 403
I am using Web Push protocol to send push notifications. I have registered a service worker and subscribed successfully with pushManager in one tab. When I send messages push event able to receive notification and logs the messages in console.
I am opening the same url and same service worker is getting registered and returning same subscription using below snippet.
serviceWorkerRegistration.pushManager.getSubscription()
But when I send messages, first tab only logs the messages in console. second tab is not logs the messages in console.
When I close the first tab and send messages, now I am able see the messages in second tab console logged by service worker.
Note: Both the tabs loaded in same origin.
Example: https://localhost:8080/WebPush
Below is my service worker code
self.addEventListener('push', function(event) {
if (event.data) {
console.log('This push event has data: ', event.data.text());
}
else {
console.log('This push event has no data.');
}
});
At the same time when I try using firebase , I am able receive messages in both the tabs.
Can anyone help me out to receive messages on both the tabs using web push.
Thanks in advance.
Upvotes: 3
Views: 2613
Reputation: 403
I have find out an one possible way to achieve this use case.
After push event triggered, using service worker clients API, I will find out number of open clients in the same origin and post message to all the clients.
Below is the code snippet need to add inside push event in the service worker.
clients.matchAll({
type: 'window',
includeUncontrolled: true
})
.then(function(windowClients)
{
windowClients.forEach(function(windowClient){
windowClient.postMessage({
message: 'Received a push message.'+event.data.text(),
time: new Date().toString()
});
});
});
And add a service worker listener.
navigator.serviceWorker.addEventListener('message', function(event) {
console.log('Received a message from service worker: ', event.data);
});
This will help to receive push messages in multiple tabs.
Upvotes: 4
Reputation: 3893
the service worker is going to respond to the push event once. This will happen in the thread spawned by the push notification. It is not going to spin up for each browser tab. In fact it will be or should be a separate instance of the service worker apart from the instance being used by any client. The client for a push notification is the OS, sort of a headless client if you will.
Yes you will see the console messages logged. I suspect Chrome's internals have the thread look for the first open client with a console to pass those messages.
I can't speak for the actual threading model employed by Chrome, FireFox, Opera, Samsung or Edge as to how the different event responses are threaded, but they should in essence be separate when it comes to fetch, push and background sync.
I hope this helps you grok the concept, but what you are seeing is what I would expect to see, one console logging the messages from the push initiated sw thread.
Upvotes: 0