navigator.serviceWorker.controller is null until p

2019-03-27 15:57发布

问题:

I work with angularjs and use service worker to receive push notification. but navigator.serviceWorker.controller is null until page refresh,and I don't know how to do to solve this problem

some code of serviceworker :

self.addEventListener('push', pwServiceWorker.pushReceived);
self.addEventListener('notificationclick', pwServiceWorker.notificationClicked);

// refresh caches
self.addEventListener('activate', function (event)
{
    event.waitUntil(
        caches.keys().then(function (cacheNames)
        {
            return Promise.all(
                cacheNames.map(function (cacheName)
                {
                    return caches.delete(cacheName);
                })
            );
        })
    );
});

and send message to the client in serviceworker when push received :

self.clients.matchAll().then(function(all) {
    console.log(all);
    all.forEach(function(client) {
        client.postMessage(data);
    });
});

in mainController.js give message like this :

 if (!navigator.serviceWorker || !navigator.serviceWorker.register) {
        console.log("This browser doesn't support service workers");
        return;
    }

    // Listen to messages from service workers.
    navigator.serviceWorker.addEventListener('message', function(event) {
        console.log("Got reply from service worker: " + event.data);
    });

    // Are we being controlled?
    if (navigator.serviceWorker.controller) {
        // Yes, send our controller a message.
        console.log("Sending 'hi' to controller");
        navigator.serviceWorker.controller.postMessage("hi");
    } else {
        // No, register a service worker to control pages like us.
        // Note that it won't control this instance of this page, it only takes effect
        // for pages in its scope loaded *after* it's installed.
        navigator.serviceWorker.register("service-worker.js")
            .then(function(registration) {
                console.log("Service worker registered, scope: " + registration.scope);
                console.log("Refresh the page to talk to it.");
                // If we want to, we might do `location.reload();` so that we'd be controlled by it
            })
            .catch(function(error) {
                console.log("Service worker registration failed: " + error.message);
            });
    }

回答1:

This is expected behavior. To take control over all open pages without waiting for refresh/reopen, you have to add these commands to your Service Worker:

self.addEventListener('install', function(event) {
    event.waitUntil(self.skipWaiting()); // Activate worker immediately
});

self.addEventListener('activate', function(event) {
    event.waitUntil(self.clients.claim()); // Become available to all pages
});

You can read more about them in skipWaiting() docs and clients.claim() docs.