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);
});
}
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With