【问题标题】:Web/Desktop Notification API - force close all notifications upon refreshing the pageWeb/Desktop Notification API - 在刷新页面时强制关闭所有通知
【发布时间】:2015-06-04 12:07:38
【问题描述】:
我一直在研究 Web 通知 API 或桌面通知 API。我了解它的构造方式以及它支持的属性和事件的数量。通知旨在与浏览器分开,以便即使浏览器最小化,例如,通知仍然可以显示。
我的问题是,有没有办法将通知与网页上的操作联系起来?特别是,我想在刷新页面时关闭所有通知对话框。我怎样才能做到这一点?
提前致谢。
【问题讨论】:
标签:
javascript
html
notifications
service-worker
web-notifications
【解决方案1】:
你没有提到服务工作者,但我假设你有一个,因为你需要它来实现推送和通知 API。
当页面加载时,您可以向服务人员发送一条消息,指示其关闭所有通知。然后,您可以像这样在工作人员中执行此操作:
self.getNotifications().then(function(notifications){
notifications.forEach(function(notification){
notification.close()
})
})
但是,您可以跳过向服务工作人员发送消息,只需通过服务工作人员注册从页面执行此操作,如下所示:
navigator.serviceWorker.getRegistration().then(function(registration){
registration.getNotifications().then(function(notifications){
notifications.forEach(function(notification){
notification.close()
})
})
})
但是,请注意 getNotifications() 仅适用于 Chrome 44。在 Chrome 44 之前,或在其他浏览器中,我不相信有办法做你想做的事。