'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?



Solution 1:[1]

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

Solution 2:[2]

Please register sw.js in your html page

        <script type="text/javascript">

                navigator.serviceWorker.register('/myproject/scripts/common/pushNotifications/sw.js').then(function(registration) {
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
                     }, function(err) {
                console.log('ServiceWorker registration failed: ', err);
                });
                
        </script>

Solution 3:[3]

A weird bug in my case as this all happened without any error on my side. Simply restarting Google chrome fixed it

Solution 4:[4]

For me, I was getting this error because there was a bug in my code, so this is why the extension keeps showing this error message even after you reload the extension or reload the browser! So make sure that your code doesn't have any bugs!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 geekme
Solution 2 pranay anugu
Solution 3 Oush
Solution 4 CoderNadir