navigator.serviceWorker.controller is always null

假如想象 提交于 2019-12-03 11:20:47

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.

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.

Try adding this in the service worker:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!