serviceworkers focus tab: clients is empty on noti

2019-02-16 06:58发布

问题:

I have a common serviceworker escenario, where I want catch a notification click and focus the tab where the notification has come from. However, clients variable is always empty, its lenght 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 this one:

 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 fine. However, when a notification is pushed, clientList is empty. I have tried removing the filter type:'window' but the result is still the same. As clients are empty, a new window is always opened. What am I doing wrong?

回答1:

The suspicion in your own comment is correct. A page is controlled by a service worker on navigation to an origin that the service worker is registered for. So the original page load that actually initializes the service worker is not itself controlled. That's why the worker only finds your tab once you visit with a new tab or do a refresh.

However (as Jeff Posnick points out in the comments) you can get uncontrolled pages as follows: ServiceWorkerClients.matchAll({includeUncontrolled: true, type: 'window'}).



回答2:

Try making the service worker immediately claim the page. E.g.:

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.