Check if window is enabled from Service Worker
I am trying to start a web application that sends push notifications when the window is inactive. For this I have a Service Worker that helps to receive notifications from my php server (via Firebase).
However, I am not sure how to check if a window is active through my Worker. The Service Worker does not have access to the DOM, so I cannot validate it right there, and I tried to perform validations in the attached JS file, but the Service Worker is getting variables not defined by errors. My Service Worker code looks like this:
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
// console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Chat';
const options = {
body: 'New message received!',
icon: '/images/logo/8-icon.png',
badge: '/images/badge.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://localhost:8000')
);
});
Can anyone enlighten me in a proper way to check the active window to prevent push notifications if the web app is active?
Thank!
source to share
You can use the visibility API -> https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API?redirectlocale=en-US&redirectslug=DOM%2FUsing_the_Page_Visibility_API
Attach an event listener on the homepage to talk to your service worker. Then the service worker can execute accordingly.
source to share
Even you can use the service worker window API to check if the web page is visible or hidden.
clients.matchAll({
type: 'window',
includeUncontrolled: true
})
.then(function(windowClients) {
var clientIsVisible = false;
for (var i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.visibilityState==="visible") {
clientIsVisible = true;
break;
}
}
return clientIsVisible;
});
source to share