Sampat
Sampat

Reputation: 1309

angular service-worker - handling push notification click

How do I handle the push notification click in angular service worker. The SWPush does not have any methods.

I have tried referencing a js which listens to the "notificationclick" event handler but it never got fired on the click of the notification button.

Upvotes: 11

Views: 7244

Answers (4)

lalithBR
lalithBR

Reputation: 11

this.swPush.notificationClicks.subscribe((result) => {
      console.log('clicked', result);
    });

This is working. But it doesn't show usefull data to route

Upvotes: 0

titusfx
titusfx

Reputation: 2026

I suggest to update angular to at least Angular version 7.1.0 ( I would suggest to maintain up to date ). With this, you can now subscribe to notificationClicks

In the constructor inject SwPush then use it with:

   this.swPush.notificationClicks.subscribe( arg =>
   {
     console.log(
       'Action: ' + arg.action,
       'Notification data: ' + arg.notification.data,
       'Notification data.url: ' + arg.notification.data.url,
       'Notification data.body: ' + arg.notification.body,
     );

  });

If you don't want to update you should watch the file ngsw-worker.js with Webpack or gulp or etc. And then after the line with this.scope.addEventListener('push', (event) => this.onPush(event)); add the following:

this.scope.addEventListener('notificationclick', (event) => {
    console.log('Notification event', event);
    event.notification.close();
    var payload = event.notification.data;

    if (event.action && payload.actions && payload.actions.includes(event.action) 
       clients.openWindow && event.notification.data.url) {
      event.waitUntil(clients.openWindow(event.notification.data.url));
    }
  });

Upvotes: 4

Barrie Galitzky
Barrie Galitzky

Reputation: 1156

I had to update my package.json to:

"@angular/service-worker": "7.1.0"

then this worked for me:

this.swPush.notificationClicks.subscribe((result) => {
      console.log('clicked', result);
    });

Upvotes: 3

Stuart Hallows
Stuart Hallows

Reputation: 8953

Call SWPush#requestSubscription. Here's a good article

Upvotes: 4

Related Questions