Cannot install service worker in Chrome

8k views Asked by At

I am trying to use service workers in Chrome on localhost:3000. My app is using AngularJS 1.5.

The service worker state is not activating. It is going from installing to redundant.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker
    .register('/service-worker.js')
    .then(function(registration) {
        var serviceWorker;
        if (registration.installing) {
            serviceWorker = registration.installing;
        } else if (registration.waiting) {
            serviceWorker = registration.waiting;
        } else if (registration.active) {
            serviceWorker = registration.active;
        }

        if (serviceWorker) {
            console.log("ServiceWorker phase:", serviceWorker.state);

            serviceWorker.addEventListener('statechange', function (e) {
                console.log("ServiceWorker phase:", e.target.state);
            });
        }
    })
    .catch(function(err) {
        console.log('Service Worker Error', err);
    });
}

Output of above script:

ServiceWorker phase: installing

ServiceWorker phase: redundant

service-worker.js is available at http://localhost:3000/service-worker.js. I don't see any error messages. What am I doing wrong?

1

There are 1 answers

0
Awn Ali On

I faced the same issue and this is how I fixed it:

  • Browse the page, which has the service worker running
  • Navigate to chrome://inspect/#service-workers in chrome browser
  • Find your service worker, which is in redundant state and click terminate

terminate the SW

  • Refresh your page which has the service worker

  • Open developer console, go to the application tab and then service worker section. you should see the green icon with your service worker now.

  • Add following function in your SW

    self.addEventListener("activate", function(event) { event.waitUntil(self.clients.claim()); });

verify the working SW