unable to post message to service worker because controller value is null

↘锁芯ラ 提交于 2019-12-10 17:18:05

问题


I am trying to make a website available offline with the help of service workers to cache the files needed by the page. I am trying to give the user control over which images he wishes to cache.

For this, I am using a function sendMessage

 function sendMessage(msg){
  navigator.serviceWorker.controller.postMessage(msg);
}

where message contains data relative to the image that the user wishes to cache or un-cache.

The service worker contains an event listener for the message event:

this.addEventListener('message', function(event){
var data = event.data;
caches.open('v1').then(function(cache){
    if(data.add==1)
        return cache.add(data.url);
    else
        cache.delete(data.url).then(function(response)      
    {
     console.log(response)});
     console.log(event);
    }
 )})

The problem I am facing is that the controller is always null.


回答1:


The problem is that your service worker is registered, but it isn't active and it isn't controlling your page yet.

If you want your service worker to become active, you can call the function skipWaiting in the install event handler.

If you want your service worker to control the page as soon as it becomes active, you can use the Clients.claim function in the activate event handler.

You can see an example in the ServiceWorker Cookbook Immediate Claim recipe.



来源:https://stackoverflow.com/questions/37050383/unable-to-post-message-to-service-worker-because-controller-value-is-null

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