Web/桌面通知 API - 在刷新页面时强制关闭所有通知

gcg*_*lar 2 html javascript notifications web-notifications service-worker

我一直在研究 Web 通知 API 或桌面通知 API。我了解它的构造方式以及它支持的属性和事件的数量。通知旨在与浏览器分开,因此即使浏览器被最小化,例如通知仍然可以显示。

我的问题是,有没有办法将通知与网页上的操作联系起来?特别是,我想在刷新页面时关闭所有通知对话框。我怎样才能做到这一点?

提前致谢。

Bre*_*hie 6

您没有提到 service worker,但我假设您有一个 service worker,因为推送和通知 API 需要它。

当页面加载时,您可以向 Service Worker 发送一条消息,指示它关闭所有通知。然后,您可以像这样在工作人员中执行此操作:

self.getNotifications().then(function(notifications){
  notifications.forEach(function(notification){
    notification.close()
  })
})
Run Code Online (Sandbox Code Playgroud)

但是,您可以将消息跳过给 Service Worker,然后通过 Service Worker 注册从页面执行此操作,如下所示:

navigator.serviceWorker.getRegistration().then(function(registration){
  registration.getNotifications().then(function(notifications){
    notifications.forEach(function(notification){
      notification.close()
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

但是,请注意,这getNotifications()仅适用于 Chrome 44。在 Chrome 44 之前或在其他浏览器中,我认为没有办法做您想做的事。