Error with Service Worker registration

2019-07-17 15:48发布

问题:

I'm trying to register a service worker but I have the following error:

Failed to register a ServiceWorker: The URL Protocol of the current origin ('null') is not supported

I'm under localhost with node js and I have my index.html and service-worker.js in the same folder

index.html

<!doctype html>
  <html>
  <head>
  <title>TryService</title>
  </head>
  <body>
  PROVA SITO CON SERVICE WORKER
  <script>
     if('serviceWorker' in navigator){
        // Register service worker
         navigator.serviceWorker.register('service-worker.js').then(function(reg){
            console.log("Registration OK!. Scope is "+reg.scope);
        }).catch(function(err){
            console.error("Registration FAILED! "+err);
        });
    }
  </script>

  </body>
  </html>

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

How can I fix it? Thank you in advance!