Service Worker Registration Failed

痴心易碎 提交于 2019-11-27 19:28:47

问题


I am currently working on service worker to handle push notification in browser. Currently I am having this "SW registration failed error". Can anyone help with this issue? Check client1.html and service-worker.js file below:

ERROR:

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

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

  <!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>

回答1:


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.

and second issue was during registration.

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



回答2:


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



来源:https://stackoverflow.com/questions/39136625/service-worker-registration-failed

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