问题
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!
回答1:
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 main page to talk to your service worker. Then the service worker can execute accordingly.
回答2:
Even you can use service worker window client API to check whether webpage 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;
});
来源:https://stackoverflow.com/questions/45150642/check-if-window-is-active-from-service-worker