【问题标题】:Cancel sent Web Push notifications取消发送的 Web 推送通知
【发布时间】:2019-11-14 13:57:32
【问题描述】:

当我的网站用户(例如)收到私人消息时,我会向他们发送推送通知。 该通知会发送给为该用户订阅的所有浏览器。台式机、移动设备、工作计算机等也是如此。

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

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

这可能吗?

提前致谢! 马特

【问题讨论】:

  • edit 成为主题的问题:包括一个重复问题的Minimal, Complete, and Verifiable example。寻求调试帮助的问题(“为什么这段代码不能按我想要的方式工作?”)必须包括:(1)期望的行为,(2)特定的问题或错误,以及(3)重现它所需的最短代码问题本身。另请参阅:What topics can I ask about here?How to Ask
  • 嗨,Rebot 先生。我不需要帮助调试代码。我只需要知道是否有任何方法可以取消(远程关闭)我已经发出的网络推送通知。我没有它的代码 - 我需要知道它是否存在或者是否可以使用 Web 推送 API。我在网上找不到任何关于它的信息

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


【解决方案1】:

是的,这是可能的,但不是静默的。例如,Chrome 会将通知替换为“此站点已在后台更新”的新通知。

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

Notification API 提供Notification.close(),用于取消通知的显示。

您可以使用 Push API 来触发Notification.close()。这是一个应该放入您的 Service Worker 的示例:

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"

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2017-01-18
    • 2021-06-11
    • 1970-01-01
    • 2018-02-17
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多