如何在一段时间后隐藏推送通知?

时间:2016-07-24 07:59:57

标签: push-notification service-worker

我必须在1分钟后隐藏推送通知。我应该如何在我的服务人员中做到这一点?

2 个答案:

答案 0 :(得分:4)

您可以使用Notification.close() method。您可以使用由Notification返回的承诺解析为的NotificationEvent对象来获取与您的通知关联的ServiceWorkerRegistration.showNotification对象。

这样的事情:

self.addEventListener('push', event => {
  event.waitUntil(
    self.registration.showNotification('Title', {
      body: 'Body.',
    })
    .then(notificationEvent => {
       let notification = notificationEvent.notification;
       setTimeout(() => notification.close(), 60000);
    })
  );
});

另一种可能的解决方案是使用ServiceWorkerRegistration.getNotifications获取您显示的所有通知。

例如:

self.addEventListener('push', event => {
  event.waitUntil(
    self.registration.showNotification('Title', {
      body: 'Body.',
    })
    .then(() => self.registration.getNotifications())
    .then(notifications => {
      setTimeout(() => notifications.forEach(notification => notification.close()), 60000);
    })
  );
});

答案 1 :(得分:1)

您必须使用 Notification.close

此外,要获得通知,您必须使用 ServiceWorkerRegistration.getNotifications()。要识别特定通知,您可以使用 Notification.tag。

最后,您必须在“waitUntil”中保持 Promise 处于活动状态,以防止 service-worker 在超时触发之前关闭:

event.waitUntil(
  self.registration.showNotification('Title', {body: 'Body.', tag: 'my-unique-tag'})
    .then(() => new Promise(resolve => setTimeout(resolve, 60000)) // keep service worker alive
    .then(() => self.registration.getNotifications())
    .then(notifications => {
      const notification = notifications.find(notification => notification.tag === 'my-unique-tag')
      if (notification) {
        notification.close()
      }
    })
  );