如何在一段时间后隐藏推送通知?
How to hide a push notification after some time?
我必须在 1 分钟后隐藏推送通知。我应该在我的 service worker 中做什么来实现这个目标?
您可以使用 Notification.close() method. You can get the Notification object with ServiceWorkerRegistration.getNotifications.
例如:
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.close。
此外,要获得通知,您必须使用 ServiceWorkerRegistration.getNotifications()。要识别特定通知,您可以使用 Notification.tag.
最后,您必须在“waitUntil”中保持 Promise 处于活动状态,以防止 service-worker 在您的超时触发之前关闭:
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()
}
})
);
我必须在 1 分钟后隐藏推送通知。我应该在我的 service worker 中做什么来实现这个目标?
您可以使用 Notification.close() method. You can get the Notification object with ServiceWorkerRegistration.getNotifications.
例如:
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.close。
此外,要获得通知,您必须使用 ServiceWorkerRegistration.getNotifications()。要识别特定通知,您可以使用 Notification.tag.
最后,您必须在“waitUntil”中保持 Promise 处于活动状态,以防止 service-worker 在您的超时触发之前关闭:
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()
}
})
);