Register service worker in angular.js application

I am creating an application using ionic and angular.js and I am having difficulty registering a service worker, which I intend to use to add a new application banner function. I am adding the code below to the app.js file as instructed, but I want to receive any registration signals and errors.

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); }); } 
+4
source share
2 answers

Make sure you load the page in localhost or you need to use https

You will also need to serve your code over HTTPS. Service workers can only work on HTTPS for security reasons. Therefore, GitHub is a good place to experiment because 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 may help: http://caniuse.com/#feat=serviceworkers

If you want to see the current status of your serviceworker, you can 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); }); 
+8
source

If you do not see anything registered, the most likely reason is that you are working in a browser that does not support service workers. In other words, an if ('serviceWorker' in navigator) check is not performed. You can confirm this by adding an else clause in the log else associated with this if .

What browser are you testing with? In the future, service workers come in more browsers, but as of now, they are enabled by default only in current versions of Chrome on desktop and Android platforms.

+1
source

Source: https://habr.com/ru/post/1268589/


All Articles