一段时间后如何隐藏推送通知? [英] How to hide a push notification after some time?

查看:57
本文介绍了一段时间后如何隐藏推送通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 1 分钟后隐藏推送通知.我应该在我的 Service Worker 中做什么来实现这一目标?

I have to hide a push notification after 1 minute. What should I do in my service worker to achieve this?

推荐答案

您可以使用 Notification.close() 方法.您可以使用Notification 对象链接到您的通知NotificationEvent 对象,由 ServiceWorkerRegistration.showNotification 解析为.

You can use the Notification.close() method. You can get the Notification object linked to your notification by using the NotificationEvent object that the promise returned by ServiceWorkerRegistration.showNotification resolves to.

像这样:

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

另一种可能的解决方案是获取您使用 ServiceWorkerRegistration.getNotifications.

Another possible solution is to get all the notifications you're showing with 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);
    })
  );
});

这篇关于一段时间后如何隐藏推送通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆