Reputation: 1489
I have to hide a push notification after 1 minute. What should I do in my service worker to achieve this?
Upvotes: 4
Views: 4165
Reputation: 10802
You can use the Notification.close() method. You can get the Notification object with ServiceWorkerRegistration.getNotifications.
For example:
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);
})
);
});
Upvotes: 7
Reputation: 794
You have to use Notification.close.
Also, to get the notifications, you have to use ServiceWorkerRegistration.getNotifications(). To identify a specific notification, you can use Notification.tag.
Finally, you must keep a Promise alive inside "waitUntil" to prevent the service-worker to shut down before your timeout triggers:
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()
}
})
);
Upvotes: 3