当我的网站用户(例如)收到私有(private)消息时,我会向他们发送推送通知。 该通知会发送给为该用户订阅的所有浏览器。也可以是台式机、移动设备、工作计算机等。
我想做的是在用户阅读消息后关闭所有已发送的通知。
所以用户在移动设备上登录,阅读私有(private)消息 - 此时我希望关闭/取消该 PM 之前发送的所有通知。
这可能吗?
提前致谢! 马特
最佳答案
是的,这是可能的,但不是悄无声息的。例如,Chrome 会将通知替换为一条新通知,内容为“此网站已在后台更新”。
有两个独立的 API:Push API它“使 Web 应用程序能够接收从服务器推送给它们的消息”,以及 Notification API “用于配置和向用户显示桌面通知”。
通知 API 提供 Notification.close()
,取消通知的显示。
您可以使用 Push API 来触发 Notification.close()
。这是您的服务 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" .
关于progressive-web-apps - 取消发送的网络推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877538/