Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register service worker in angular.js application

I'm creating an app using ionic and angular.js and I'm having difficulties registering a service worker which I'm intending to use to add the new app install banner feature. I'm adding the below code on my app.js file as instructed, but I'm note getting any signals of the registration happening nor any error.

This is the code I'm adding to my app.js:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('service-worker.js').then(function(registration) {
    //Registration was successful
    console.log('ServiceWorker registration successful with scope: ', registration.scope);
  }).catch(function(err) {
    //registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
}
like image 422
George Cscnt Avatar asked May 15 '15 22:05

George Cscnt


2 Answers

Make sure you either load the page at localhost or you have to use https

You’ll also need to serve your code via HTTPS — Service Workers are restricted to running across HTTPS for security reasons. GitHub is therefore a good place to host experiments, as it supports HTTPS.

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers

Check if your Browser supports this feature.

if ('serviceWorker' in navigator) {
  [...]
} else {
  console.log("this browser does NOT support service worker");
}

This might help: http://caniuse.com/#feat=serviceworkers

If you want to see the current state of your serviceworker you could do something like this:

navigator.serviceWorker.register('/serviceworker.js', {scope: '/'})
  .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('ServiceWorker registration failed: ', err);
  });
like image 124
Alexander B. Avatar answered Sep 19 '22 13:09

Alexander B.


If you're not seeing anything logged, then the most likely cause is that you're running in a browser that doesn't support service workers. In other words, the if ('serviceWorker' in navigator) check fails. You can confirm this by adding in a logging statement in an else clause associated with that if.

Which browser are you testing with? Service workers are coming to more browsers in the future, but as of right now, they're only enabled by default in the current versions of Chrome on desktop and Android platforms.

like image 30
Jeff Posnick Avatar answered Sep 22 '22 13:09

Jeff Posnick