In my calendar application I want to send notifications X minutes before events.
I used the notification API with service worker as follow :
I register the service worker in my index.html
.
// Registering my service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', {
scope: '/'
})
.then(function(reg) {
window.swReg = reg;
console.log('registration succeed');
}).catch(function(error) {
console.log('Registration failed with ' + error);
});
}
Elsewhere in my app, I used a setTimeout to trigger the notification :
// Show notification at next event
setTimeout(() => {
swReg.showNotification('Your event starts in 5mn!')
.then(ev => {
console.log(ev); // <= got undefined!
});
}, delayBeforeNextEvent);
Regarding of the specifications, MDN/showNotification#Syntax I should be able to access the NotificationEvent
through the ev
parameter of the resolved promise.
But the promise is resolved immediately and ev
is undefined.
For the instance I have to define an event listener inside my service-worker.js
to get it working but I want to keep this logic next to the code above.
self.addEventListener('notificationclick', ev => {
ev.notification.close();
});
Any ideas ?