navigator.serviceWorker.controller is always null

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.


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


Try adding this in the service worker:

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

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.