Finding the number of active push notifications from service worker

戏子无情 提交于 2019-12-11 06:31:47

问题


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);
    })
  );
});

回答1:


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
}) 


来源:https://stackoverflow.com/questions/45968851/finding-the-number-of-active-push-notifications-from-service-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!