Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
Saugat Bhattarai Avatar asked Aug 25 '16 04:08

Saugat Bhattarai


People also ask

How do I know if a service is registered or not?

You can look at Service Worker Detector, a Chrome extension that detects if a website registers a Service Worker by reading the navigator. serviceWorker.

How do I register a service worker in HTML?

register() The register() method of the ServiceWorkerContainer interface creates or updates a ServiceWorkerRegistration for the given scriptURL . If successful, a service worker registration ties the provided script URL to a scope, which is subsequently used for navigation matching.

What is ServiceWorkerRegistration?

The ServiceWorkerRegistration interface of the Service Worker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin.


3 Answers

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){ 
like image 89
Saugat Bhattarai Avatar answered Sep 19 '22 23:09

Saugat Bhattarai


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

like image 23
geekme Avatar answered Sep 19 '22 23:09

geekme


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

like image 41
Oush Avatar answered Sep 20 '22 23:09

Oush