问题
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