有没有一种方法可以在显示后删除Web推送通知?从设备的通知列表中删除它-或将其标记为“已读”?
我认为这不能从服务器上完成,我一直在寻找JavaScript API-但我没有找到任何内容。
(我试图解决的更广泛的问题是如何在多个屏幕/浏览器/设备上同步通知。)
有没有一种方法可以在显示后删除Web推送通知?从设备的通知列表中删除它-或将其标记为“已读”?
我认为这不能从服务器上完成,我一直在寻找JavaScript API-但我没有找到任何内容。
(我试图解决的更广泛的问题是如何在多个屏幕/浏览器/设备上同步通知。)
尽管无法撤销推送消息,但可以使用以下方法关闭一个:
// app.js
navigator.serviceWorker.ready.then(reg => {
reg.getNotifications().then(notifications => {
for (let i = 0; i < notifications.length; i += 1) {
notifications[i].close();
}
});
});
data: { action: 'close', id: 123 }
,以触发关闭消息。'push'事件监听器可以将'message'事件传递给所有客户端,以关闭给定(或所有)打开的通知。// sw.js
self.addEventListener('push', event => {
let opts = event.data.json();
if (opts.data && opts.data.action) {
event.waitUntil(clients.matchAll().then(windowClients => {
for (let i = 0; i < windowClients.length; i += 1) {
windowClients[i].postMessage(opts.data);
}
});
}
});
// app.js
navigator.serviceWorker.addEventListener('message', event => {
if (event.data && event.data.action && event.data.action === 'close') {
closeNotification(event.data.id);
}
});
function closeNotification(id) {
navigator.serviceWorker.ready.then(reg => {
reg.getNotifications().then(n => {
for (let i = 0; i < n.length; i += 1) {
if (n[i].data && n[i].data.id && n[i].data.id === id) {
n[i].close();
}
}
});
});
}
只有在接收到推送消息并且服务工作者中的推送事件在传递给event.waitUntil()的promise完成后没有显示通知时,Chrome才会显示“此站点已在后台更新。”通知。
event.waitUntil(
self.registration.showNotification(title, options)
.then(function (data) {
self.registration.getNotifications()
.then(function (notifications) {
setTimeout(function () {
//console.log(notifications);
notifications.forEach(notification => notification.close())
}, 10);
})
})
);
setTimeout(function {}, duration);
的定义中,duration 是以毫秒为单位的。 - Serge Stroobandt
event.waitUntil()
等即可。 - Gary GreenPushManager.subscribe
具有设置为true的userVisibleOnly
选项,该选项是必需的。 - collimarco