2

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 ?

Jordan Martin
  • 176
  • 2
  • 5
  • Are you aiming for web push notifications or just notifications? Because for plain js notifications there is no need for service worker, they work as long as page is open, service worker is for web push notifications and they work as long browser is running (not the page), but to send such notification you would need user notifications subscription and API call to web push endpoint. But either way you need to ask permission to display notifications before you try to display one. – Mr_KoKa Sep 24 '17 at 00:46
  • @Mr_KoKa One reason for always using the current service-worker based notifications mechanism (even for non-push notifications) is that the old non-service-worker way (using the Notification constructor) isn’t supported in Chrome on Android; only the current service-worker based notifications mechanism works there. See the answer at https://stackoverflow.com/questions/31512504/html5-notification-not-working-in-mobile-chrome/31787926#31787926 – sideshowbarker Sep 24 '17 at 01:28
  • Like @sideshowbarke said, I need to support notification on android. I also use service worker to send notification even if the page is not opened. I already request the permission for notificatino elsewhere in the app and it's working, I can send the notification. – Jordan Martin Sep 24 '17 at 23:32

0 Answers0