I am using the below script to register service worker, and would like to Check if this service worker supports push? Just for testing purpose I am printing 'Print Service worker', but it is not getting printed to console. Kindly help me to trigger where I am getting wrong?
function register()
{
if ('serviceWorker' in navigator)
{
navigator.serviceWorker.register('service-worker.js', {scope: scope}).then(initialiseState);
}
else {
console.warn('Service workers aren\'t supported in this browser.');
}
}
function initialiseState()
{
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration)
{ console.log('Print Service worker');});
}
Thanking in advance
First, an explanation as to why you aren't seeing the logging you expect:
Unless you call self.clients.claim()
within your service worker, it won't take control of the current web page during the navigation when its initially registered. As for the navigator.serviceWorker.ready
promise, it doesn't resolve until there's a service worker that controls the page. Put those two together and I would not expect your console.log()
to execute the first time you visit the page, but I would expect it on subsequent visits (if the service worker installed properly).
There's an example of using self.clients.claim()
if you want to have your service worker take control of the page the very first time you navigate there.
As to your actual question, if you feel the need to feature-detect service worker push support, you should be able to just check for 'pushManager' in registration
, where registration
is a ServiceWorkerRegistration
object, like the one navigator.serviceWorker.register()
resolves with. There's no need to wait until your page is controlled by a service worker. So this should work:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
if ('pushManager' in registration) {
// The service worker supports push
} else {
// The service worker doesn't support push
}
});
} else {
// The browser doesn't support service workers
}