Javascript Service Worker 注册失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39136625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:15:28  来源:igfitidea点击:

Service Worker Registration Failed

javascriptbrowserservice-workerweb-push

提问by Saugat Bhattarai

I am currently working on service worker to handle push notification in browser. Currently I am having this "SW registration failed error":

我目前正在使用 Service Worker 来处理浏览器中的推送通知。目前我有这个“软件注册失败错误”:

SW registration failed with error SecurityError: Failed to register a ServiceWorker: The URL protocol of the current origin ('null') is not supported.

SW 注册失败,错误为 SecurityError: Failed to register a ServiceWorker: The URL protocol of the current origin ('null') is not supported.

Check client1.htmland service-worker.jsfile below:

检查client1.htmlservice-worker.js归档如下:

service-worker.js

service-worker.js

console.log('Started', self);
self.addEventListener('install', function(event) {
  self.skipWaiting();
  console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
  console.log('Activated', event);
});
self.addEventListener('push', function(event) {
  console.log('Push message received', event);
});

client1.html

客户端1.html

<!doctype html>
<html>
  <head>
    <title>Client 1</title>
  </head>
  <body>
    <script>
      if('serviceWorker' in navigator){
        // Register service worker
        navigator.serviceWorker.register('service-worker.js').then(function(reg){
          console.log("SW registration succeeded. Scope is "+reg.scope);
        }).catch(function(err){
          console.error("SW registration failed with error "+err);
        });
      }
    </script>
  </body>
</html>

Can anyone help with this issue?

任何人都可以帮助解决这个问题吗?

回答by Saugat Bhattarai

Solved:First thing is service worker only works in secure mode either in https or localhost. It doesnot work in local resources like file:// or http.

已解决:第一件事是 Service Worker 只能在 https 或 localhost 的安全模式下工作。它不适用于 file:// 或 http 等本地资源。

and second issue was during registration.

第二个问题是在注册期间。

     navigator.serviceWorkerContainer.register('service-worker.js').then(function(reg){

回答by geekme

Use chrome webserver, to run the app or just a simple command in terminal(Mac) would do. python -m SimpleHTTPServer

使用 chrome 网络服务器来运行应用程序,或者只是在终端(Mac)中使用一个简单的命令就可以了。python -m SimpleHTTPServer