Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

javascript - Service Worker Registration Failed

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

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

Check client1.html and service-worker.js file below:

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>

Can anyone help with this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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){

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...