Push notification 如何在一段时间后隐藏推送通知?
我必须在1分钟后隐藏推送通知。我应该在我的服务人员中做些什么来实现这一点?您可以使用。您可以通过使用承诺返回的对象来获取与通知链接的对象 大概是这样的:Push notification 如何在一段时间后隐藏推送通知?,push-notification,service-worker,Push Notification,Service Worker,我必须在1分钟后隐藏推送通知。我应该在我的服务人员中做些什么来实现这一点?您可以使用。您可以通过使用承诺返回的对象来获取与通知链接的对象 大概是这样的: self.addEventListener('push', event => { event.waitUntil( self.registration.showNotification('Title', { body: 'Body.', }) .then(notificationEvent =>
self.addEventListener('push', event => {
event.waitUntil(
self.registration.showNotification('Title', {
body: 'Body.',
})
.then(notificationEvent => {
let notification = notificationEvent.notification;
setTimeout(() => notification.close(), 60000);
})
);
});
另一种可能的解决方案是获取所有显示的通知
例如:
self.addEventListener('push', event => {
event.waitUntil(
self.registration.showNotification('Title', {
body: 'Body.',
})
.then(() => self.registration.getNotifications())
.then(notifications => {
setTimeout(() => notifications.forEach(notification => notification.close()), 60000);
})
);
});
你必须使用
此外,要获取通知,您必须使用。要标识特定通知,可以使用notification.tag
最后,您必须在“waitUntil”中保持承诺,以防止服务工作者在触发超时之前关闭:
event.waitUntil(
self.registration.showNotification('Title', {body: 'Body.', tag: 'my-unique-tag'})
.then(() => new Promise(resolve => setTimeout(resolve, 60000)) // keep service worker alive
.then(() => self.registration.getNotifications())
.then(notifications => {
const notification = notifications.find(notification => notification.tag === 'my-unique-tag')
if (notification) {
notification.close()
}
})
);
promise中的notificationEvent变量未定义,因此它没有关闭。请帮忙!!尝试另一种解决方案。从Chrome版本59.0.3071.115(官方版本)(64位)开始,第二种解决方案工作异常。每当我从我的服务器推送消息时,我都会收到默认的显示通知(此网站已在后台更新)。根据规范,第一个示例不起作用,因为承诺将解析为未定义。关于第二个示例,当您在Chrome(windows,版本73.0.3683.103官方版本64位)上使用
getNotifications
时使用showNotification
后,在发送多个通知后,只有最后一个通知会触发self。在通知上单击