由于控制器值为空,因此无法向服务人员发布消息 [英] unable to post message to service worker because controller value is null

查看:42
本文介绍了由于控制器值为空,因此无法向服务人员发布消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在服务工作者的帮助下使网站脱机可用页面所需的文件。
我试图让用户控制他希望缓存的图像。

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.

为此,我正在使用功能 sendMessage

For this, I am using a function sendMessage

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

其中消息包含与用户希望缓存或取消保存的图像有关的数据-cache。

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);
    }
 )})

我面临的问题是控制器始终为 null

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

推荐答案

问题是您的服务人员已注册,但尚未激活,并且尚未控制您的页面。

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

如果您希望服务人员成为活跃人员,则可以调用函数 skipWaiting install 事件处理程序中。

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

如果您希望服务人员在页面激活后立即对其进行控制,则可以使用 Clients.claim 函数在 activate 事件处理程序中。

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.

您可以在 ServiceWorker Cookbook立即提出索赔的食谱中查看示例

这篇关于由于控制器值为空,因此无法向服务人员发布消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆