php_nub_qq
php_nub_qq

Reputation: 16065

Service worker notification promise broken?

From MDN I see that showNotification returns a promise that should resolve to a NotificationEvent.

Syntax

​ServiceWorkerRegistration.showNotification(title, [options]).then(function(NotificationEvent) { ... });

Returns

A Promise that resolves to a NotificationEvent.

However I have set it up here, the notification is being sent and all but if you look at the console you will notice that event is undefined.

navigator.serviceWorker.register('worker.js');

Notification.requestPermission(function (result) {
    if (result === 'granted') {
        navigator.serviceWorker.ready.then(function (registration) {
            registration.showNotification('Laff', {
                body: 'Hello, you have unread mesages!',
                icon: '/apple-touch-icon.png',
                tag: 'test'
            }).then(function(event){
                console.log(event);
            });
        });
    }
});

I need to get a hold of the notification, which I thought I could do from event.notification but since event is undefined I don't really know what to do.

Am I doing something wrong?

Upvotes: 3

Views: 1942

Answers (2)

Sébastien Rosset
Sébastien Rosset

Reputation: 1531

Indeed there is a problem in the docs, the showNotification method doesn't return a NotificationEvent object.

If you don't want to wait for the click, you can use the getNotifications method. Here's a code to close the notification after 3 seconds.

self.registration.showNotification(...).then(() => {
    self.registration.getNotifications({tag: ...}).then(notifications => {
      setTimeout(() => notifications[0].close(), 3000);
    });
  }
})

More informations here: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/getNotifications

Upvotes: 1

kapoorji
kapoorji

Reputation: 156

I am not sure what exactly you mean of getting hold on notification ? if you are looking to capture an event when user will click on notification, you can do by adding listener.

add return .

return registration.showNotification('Laff', {

catch the event on notificationClick:

    self.addEventListener('notificationclick', function (event) {

        var tag = event;
}

hope it helps

Upvotes: 1

Related Questions