取消发送的Web推送通知

时间:2019-07-03 20:29:54

标签: progressive-web-apps web-push web-notifications

当我的网站用户(例如)收到私人消息时,我正在向他们发送推送通知。 该通知将发送给该​​用户订阅的所有浏览器。台式机,移动设备,办公计算机等也可以。

我想做的是在用户阅读邮件后关闭所有已发送的通知。

因此,用户登录移动设备后,会读取私人消息-此时,我希望关闭/取消该PM以前发送的所有通知。

这可能吗?

提前谢谢! 马特

1 个答案:

答案 0 :(得分:0)

是的,这是可能的,但不是无声的。例如,Chrome会将通知替换为新的通知,内容为“此网站已在后台更新”。

有两个单独的API:Push API“使Web应用程序能够接收从服务器推送到它们的消息”,以及Notification API“用于配置和显示桌面通知给用户”。

Notification API提供了Notification.close(),可取消显示通知。

您可以使用Push API触发Notification.close()。这是应该送给服务人员的示例:

self.addEventListener('push', async event => {
  const data = event.data.json();
  if (data.type === 'display_notification') {
    self.registration.showNotification(data.title, data.options);
  } else if (data.type === 'cancel_notification') {
    const notifications = await self.registration.getNotifications({
      tag: data.notificationTag
    });
    for (notification of notifications) {
      notification.close();
    }
  } else {
    console.warn("Unknown message type", event, data);
  }
});

但是!这种设计意味着您的cancel_notification消息将不会显示通知。这违反了某些浏览器策略,例如Chrome will display a new notification saying "This site has been updated in the background"

相关问题