I'm trying to run a Web Application that sends push notifications when the window is inactive. To do this, I have a Service Worker that helps receives notifications from my php server (through Firebase).
However, I'm unsure how to check if the window is active through my Service worker. The Service Worker does not have access to the DOM, so I can't check it directly through there, and I've tried doing the checks on an attached JS file, but the Service Worker gets variable not defined errors. My Service Worker code is as follows:
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')
);
});
Could anyone enlighten me on the proper way to check for an active window to prevent push notifications if the web app is active?
Thanks!