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

Sup*_*acy 3 push-notification service-worker

我必须在 1 分钟后隐藏推送通知。我应该在我的服务工作者中做什么来实现这一目标?

Mar*_*rco 7

您可以使用Notification.close() 方法。您可以使用ServiceWorkerRegistration.showNotification返回的承诺解析为的NotificationEvent对象来获取链接到您的通知的Notification对象。

像这样的东西:

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

另一种可能的解决方案是使用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);
    })
  );
});
Run Code Online (Sandbox Code Playgroud)