问题
I have the problem that after registering the serviceWorker the navigator.serviceWorker.controller is always null. I never do a force refresh and just refresh the page. I test it with Google Chrome 42.0.2311.152 m (32-Bit).
var currentServiceWorker = null;
navigator.serviceWorker.register(SERVICE_WORKER_URL).then(function(serviceWorkerRegistration {
if (navigator.serviceWorker.controller) {
currentServiceWorker = navigator.serviceWorker.controller;
} else {
currentServiceWorker = serviceWorkerRegistration.active;
}
});
According to this:
The controller read-only property of the ServiceWorkerContainer interface returns a ServiceWorker object if its state is activated (the same object returned by ServiceWorkerRegistration.active). This property returns null if the request is a force refresh (Shift + refresh) or if there is no active worker. ( Source: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller)
navigator.serviceWorker.controller
should return the same object as serviceWorkerRegistration.active
. But with .active
I get the active worker, with .controller
not.
Do you have any ideas for that situation?
Thank you, Andi
回答1:
The first thing I'd look at when debugging this is whether the current page you're on falls under the scope of the service worker. If your current page isn't under the scope, then it won't be controlled (but the service worker you registered can still be considered active).
You're calling register(SERVICE_WORKER_URL)
which will, by default, use the directory that contains your service worker script as the scope. That's normally what you'd want, but you need to make sure that SERVICE_WORKER_URL
refers to a script that's located at the root of your web site. That way, it will be able to control pages both at the same root level, or pages in directories underneath your web root. So if your service worker JavaScript file is currently under a /scripts/
subdirectory or something like that, move it up to the root.
You can check the current scope of your service worker by visiting chrome://serviceworker-internals/
and seeing what the scope associated with your registration is.
回答2:
navigator.serviceWorker.register only register the serviceworker and activate it. but to get controller over the serviceworker you need to put your serviceworker in the public root folder so that all the pages will be in the scope and service worker will be attached to it.
回答3:
Try adding this in the service worker:
self.addEventListener('activate', event => {
clients.claim();
console.log('Ready!');
});
回答4:
The clients.claim() answer did it for me, along with a controller changed listener :
navigator.serviceWorker.addEventListener("controllerchange", (evt) => {
console.log("controller changed");
this.controller = navigator.serviceWorker.controller;
});
Thanks Kushagra Gour
来源:https://stackoverflow.com/questions/30256390/navigator-serviceworker-controller-is-always-null