2

I’ve implemented push notifications using service workers. Is there any way to find out the number of notifications which are currently shown in the window? My intention is to limit the number of notifications shown in the window.

I tried the following. But the getNotifications function returning me empty array.

self.addEventListener('push', function(event) {
 if (!(self.Notification && self.Notification.permission === 'granted')) {
      return;
  }
  var data = event.data.json();
  var options = {
    body: data.notificationText,
    icon: 'files/assets/staff.png',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      onClickUrl: data.onClickUrl,
      event_id: data.event_id,
      productName: data.product_name
    }
  };

  event.waitUntil(
    self.registration.getNotifications().then(function(notifications) {
      console.log(notifications);
      if (notifications && notifications.length > 0) {
        notifications.forEach(function(notification) {
          notification.close();
        });
      }
      showNotification(data.title, options);
    })
  );
});
Stanly
  • 663
  • 1
  • 9
  • 26

1 Answers1

3

You can use serviceWorker.getNotifications() which returns a list of notifications. You can use it like so:

navigator.serviceWorker.register('sw.js');

navigator.serviceWorker.ready.then(function(registration) {
  registration.getNotifications().then(function(notifications) {
    // get the number of notifications
  }) 
});

if you're doing this in your serviceworker file, it's:

self.registration.getNotifications().then(function(notifications) {
  // get the number of notifications
}) 
jedijulia
  • 126
  • 1
  • 2
  • The count is 0, event if there are notifications which are shown to the user. self.addEventListener('push', function(e) { var data = e.data.json(); var options = { body: data.notificationText, icon: 'files/assets/staff.png', data: { dateOfArrival: Date.now() } }; e.waitUntil( self.registration.getNotifications().then(function(notifications) { console.log(notifications.length); self.registration.showNotification(data.title, options) }) ); }); – Stanly Aug 31 '17 at 09:36
  • Before calling shownotification, I want to know if there are any notifications which are already shown. – Stanly Aug 31 '17 at 09:44
  • 1
    Note that getNotifications() only returns notifications from the serviceworker and notifications shown by other apps won’t be counted – jedijulia Sep 05 '17 at 04:24
  • I updated my code in the question. I am getting count as 0 when it displays 5 notifications from the same service worker. – Stanly Sep 25 '17 at 14:22