I'm trying to make periodic bg sync where service worker updates badge. When I run my page and test it via Chrome DevTools, Service worker process the request. But when the page is closed, it doesnt't do anything. Same on mobile phone.
On my page (this part is working and output in console is periodic update set):
navigator.permissions.query({name:'periodic-background-sync'}).then(function(result) {
if (result.state === 'granted') {
console.log('periodic background granted');
navigator.serviceWorker.ready.then(function(registration){
if ('periodicSync' in registration) {
try {
registration.periodicSync.register('update-badge', {
minInterval: 60 * 60 * 1000,
}).then(function(ret){
console.log('periodic update set');
});
} catch (error) {
console.log('Periodic background sync cannot be used.');
}
}
});
}
});
Service worker:
async function updateBadge() {
const unreadCount = 5; //fixed value for testing
navigator.setAppBadge(unreadCount).catch((error) => {
console.log('Error setting badge.');
});
}
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'update-badge') {
event.waitUntil(updateBadge());
}
});
So when I manually fire background sync from DevTools, badge is set, but not automatically in the background as I thought it will work.
The specific interval at which the periodicsync event is fired varies; what I've seen on, e.g., installed Android web apps is that you'll get periodicsync around once a day. It may be different on desktop platforms (and will only happen if your browser is actually running at the time).
Have you waited a full day or so after installing your PWA, and see if it's fired?
I can't find anything wrong with the code. I've seen variants where you request periodic-background-sync after navigator.serviceWorker.ready but I think that both work (especially since you can trigger the registered event manually).
I think the problem is that not all conditions for periodic background sync to fire are true. These are the conditions from the initial implementation in Chrome (2019):
In your case I think your code is correct and working but you haven't interacted enough with you app continuously over 36h so the engagement is purged and periodicsync fire timer cancelled (if you have installed your PWA).
For the record, here is a complete working demo (event registration) (and sw code).