Navigator.serviceWorker.controller is always null

I had a problem that after registering serviceWorker navigator.serviceWorker.controller is always null. I never refresh the power and just refresh the page. I am testing it using 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; } }); 

Regarding this:

The read-only property of the ServiceWorkerContainer interface controller returns a ServiceWorker object if its state is activated (the same object is returned by ServiceWorkerRegistration.active). This property returns null if the request is a strength update (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 an active worker, with .controller not.

Do you have any ideas for this situation?

Thanks Andi

+11
google-chrome service-worker
source share
4 answers

The first thing I would look at when debugging is whether the current page you are on falls within the scope of the worker. If your current page is not under an area, then it will not be controlled (but a registered service worker can still be considered active).

You call register(SERVICE_WORKER_URL) , which by default will use the directory that contains your working script service as the scope. This is usually what you need, but you need to make sure SERVICE_WORKER_URL refers to the script located at the root of your website. Thus, he will be able to control pages both at one root level, and on pages in directories under your web root. Therefore, if your JavaScript service file is running in the /scripts/ subdirectory or something like that, move it to the root directory.

You can check the current scope of your service worker by visiting chrome://serviceworker-internals/ and see what scope is associated with your registration.

+12
source share

navigator.serviceWorker.register only register serviceworker and activate it. but in order to get a controller over the serviceworker, you need to put your serviceworker in the public root folder so that all pages are in the area and the service worker will be attached to it.

+2
source share

Try adding this to a service worker:

 self.addEventListener('activate', event => { clients.claim(); console.log('Ready!'); }); 
0
source share

The .claim () client response did this for me, along with the controller changed the listener:

 navigator.serviceWorker.addEventListener("controllerchange", (evt) => { console.log("controller changed"); this.controller = navigator.serviceWorker.controller; }); 

Thanks Kushagra Gur

0
source share

All Articles