简体   繁体   English

为什么 Service Worker 在 Chrome 中不起作用?

[英]Why is Service worker not working in Chrome?

I am new to web development so sorry if I'm not clear with my question.我是网络开发的新手,如果我不清楚我的问题,我很抱歉。

I am trying to make a PWA and am currently testing to see if my manifest and service worker are working.我正在尝试制作 PWA,目前正在测试我的清单和服务工作者是否正在工作。 In my project, I have an index.html file which calls the file app.js, in which I try to register the service worker named serviceworker.js.在我的项目中,我有一个 index.html 文件,它调用文件 app.js,我尝试在其中注册名为 serviceworker.js 的服务工作者。 Here is the segment of code where I try to register my service worker:这是我尝试注册我的服务工作者的代码段:

if('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/serviceworker.js')
  .then(function() {
    console.log('service worker registered');
  });
}
else {
  console.log('cannot register');
}

When I reload my page, my console displays "cannot register".当我重新加载我的页面时,我的控制台显示“无法注册”。 To troubleshoot this, I wrote a line in the if clause to see if it was a problem with the condition itself.为了解决这个问题,我在 if 子句中写了一行,看看它是否是条件本身的问题。 Turns out, Even by removing the if and else clauses and simply running the navigator.serviceWorker.register('/serviceworker.js') .then(function() { console.log('service worker registered'); });事实证明,即使删除 if 和 else 子句并简单地运行navigator.serviceWorker.register('/serviceworker.js') .then(function() { console.log('service worker registered'); }); segment of the code, the console displays an error say "cannot find property register".代码段,控制台显示错误提示“找不到属性寄存器”。 From what I understand, service workers do not work on all browsers, but I checked to see if it runs in Chrome (which is what I'm testing in) and it says that service workers are supported.据我了解,Service Worker 并不适用于所有浏览器,但我检查了它是否在 Chrome 中运行(这是我正在测试的),并且它表示支持 Service Worker。 Can someone please tell me why it isn't working?有人可以告诉我为什么它不起作用吗? I'm currently using Version 80.0.3987.149 (Official Build) (64-bit) of Chrome.我目前正在使用 Chrome 的 80.0.3987.149(官方版本)(64 位)版本。 Alsi, I don't know if this is important, but I am using Node.js. Alsi,我不知道这是否重要,但我正在使用 Node.js。 Thanks in advance.提前致谢。

Cannot comment because of low reputation, but check this & this out.由于声誉低,无法发表评论,但请检查

In short: Service workers requires the site using them to be served over HTTPS for security reasons, but have execptions for localhost.简而言之:出于安全原因,Service Workers 要求使用它们的站点通过 HTTPS 提供服务,但对 localhost 有 execptions。

Check this for how to serve your html file on localhost.检查以了解如何在本地主机上提供您的 html 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM