【问题标题】:Finding the number of active push notifications from service worker查找来自 service worker 的活动推送通知的数量
【发布时间】:2017-09-25 22:21:04
【问题描述】:

我已经使用 Service Worker 实现了推送通知。有什么方法可以找出窗口中当前显示的通知数量?我的目的是限制窗口中显示的通知数量。

我尝试了以下方法。但是 getNotifications 函数返回我的空数组。

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

【问题讨论】:

    标签: notifications push service-worker


    【解决方案1】:

    您可以使用返回通知列表的serviceWorker.getNotifications()。你可以这样使用它:

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

    如果您在 serviceworker 文件中执行此操作,则为:

    self.registration.getNotifications().then(function(notifications) {
      // get the number of notifications
    }) 
    

    【讨论】:

    • 计数为 0,如果有通知显示给用户的事件。 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) } ) ); });
    • 在调用 shownotification 之前,我想知道是否有任何通知已经显示。
    • 请注意,getNotifications() 仅返回来自 serviceworker 的通知,其他应用显示的通知不会被计算在内
    • 我更新了问题中的代码。当它显示来自同一服务人员的 5 个通知时,我的计数为 0。
    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多