Serviceworkers focus tab: clients are blank on notification

I have a generic serviceworker escenario where I want to catch a notification and focus on the tab where the notification came from. However, the client variable is always empty; its length is 0

console.log("sw startup"); self.addEventListener('install', function (event) { console.log("SW installed"); }); self.addEventListener('activate', function (event) { console.log("SW activated"); }); self.addEventListener("notificationclick", function (e) { // Android doesn't automatically close notifications on click console.log(e); e.notification.close(); // Focus tab if open e.waitUntil(clients.matchAll({ type: 'window' }).then(function (clientList) { console.log("clients:" + clientList.length); for (var i = 0; i < clientList.length; ++i) { var client = clientList[i]; if (client.url === '/' && 'focus' in client) { return client.focus(); } } if (clients.openWindow) { return clients.openWindow('/'); } })); }); 

And the registration is as follows:

  this.doNotify = function (notification) { if ('serviceWorker' in navigator) { navigator.serviceWorker.register('sw.js').then(function (reg) { requestCreateNotification(notification, reg); }, function (err) { console.log('sw reg error:' + err); }); } ... } 

chrome: // serviceworker-internals / output shows that registration and installation are OK. However, when clicked, clientList is empty. I tried to remove the filter type: "window", but the result is still the same. Since customers are empty, a new window opens. What am I doing wrong?

+8
google-chrome service-worker
source share
2 answers

The suspicion in your own comment is true. The page is controlled by the service worker when navigating to the place of origin for which the work service is registered. Thus, the initial loading of the page, which actually initializes the service worker, is itself not controlled. This is why a worker only finds your tab after a visit with a new tab or update.

However (as Jeff Poskick points out in the comments) you can get out of control pages like this: ServiceWorkerClients.matchAll({includeUncontrolled: true, type: 'window'}) .

+16
source share

Try to contact a service person immediately. For example:.

 self.addEventListener('install', event => event.waitUntil(self.skipWaiting())); self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); 

For a more complex example, see https://serviceworke.rs/immediate-claim.html .

+1
source share

All Articles