Service Worker controllerchange never fires

◇◆丶佛笑我妖孽 提交于 2020-07-20 17:01:45

问题


I want to send a message to a service worker every time the page loads.

The first time the page loads it calls register() and then listens for the "controllerchange" event on navigator.serviceWorker but this never fires.

How do I know when I can start postMessaging a service worker?

navigator.serviceWorker.register(swURL).then(function(){
    var sw;

    if (navigator.serviceWorker.controller) {
        sw = navigator.serviceWorker.controller;
        sw.postMessage('ping');
        return;
    }

    function onchange(){
        sw = navigator.serviceWorker.controller;
        sw.postMessage('ping');
        navigator.serviceWorker.removeEventListener('controllerchange', onchange);
    }

    navigator.serviceWorker.addEventListener('controllerchange', onchange);
}).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
});

回答1:


How do I know when I can start postMessaging a service worker?

Just focusing on that bit: I'd recommend the following approach, which makes use of the navigator.serviceWorker.ready promise:

// navigator.serviceWorker.ready can be used from anywhere in your
// page's JavaScript, at any time.
// It will wait until there's an active service worker, 
// and then resolve with the service worker registration
navigator.serviceWorker.ready.then(registration => {
  registration.active.postMessage('ping');
});

If you do want to get to the bottom of why your controllerchange event listener isn't firing, my guess would be that you're not using clients.claim() in your service worker's activate event, which means the newly-activated service worker won't take control of the current page.




回答2:


The reason it's not firing is because you are registering the controllerchange event after the Service Worker has already installed/activated. So this event will fire for new Service Workers, e.g. ones that use skipWaiting(). But not for the initial Service Worker.

Use navigator.serviceWorker.ready promise which resolves as soon as there is an active Service Worker detected, no matter when it was installed/activated.



来源:https://stackoverflow.com/questions/40161452/service-worker-controllerchange-never-fires

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