Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking the action part of @angular/service-worker push notifications

Tags:

angular5

I've been trying to redirect users to the "action" part of Web push coming from the backend (PHP).

    return (new WebPushMessage)
        ->title('Title')
        ->icon('icon.png')
        ->body('Body Msg')
        ->action('Open Notification', 'open_notification')
        ->data(['id' => $notification->id,'url'=>'http://somewhere']);

Default service workers use:

self.addEventListener('notificationclick', function(event) {
    console.log('On notification click: ', event.notification.tag);
    event.notification.close();

    // This looks to see if the current is already open and
    // focuses if it is
    event.waitUntil(clients.matchAll({
       type: "window"
    }).then(function(clientList) {
       for (var i = 0; i < clientList.length; i++) {
          var client = clientList[i];
              if (client.url == '/' && 'focus' in client)
                 return client.focus();
       }
       if (clients.openWindow)
          return clients.openWindow('/');
    }));
});

From https://developer.mozilla.org/en-US/docs/Web/Events/notificationclick

Angular 5 uses

import {SwPush, SwUpdate} from '@angular/service-worker'; 

My question then is how to interpret this in the front end (Angular 5) using @angular/service-worker

like image 549
BolajiPemipo Avatar asked Feb 25 '18 11:02

BolajiPemipo


1 Answers

Got a response from u-ryo on Github

There is a workaround. Add the codes below to ngsw-worker.js around the line this.scope.addEventListener('push', (event) => this.onPush(event));(Line 1775).

  this.scope.addEventListener('notificationclick', (event) => {
    console.log('[Service Worker] Notification click Received. event', event);
    event.notification.close();
    if (clients.openWindow && event.notification.data.url) {
      event.waitUntil(clients.openWindow(event.notification.data.url));
    }
  });

Then you can specify the URL in the "notification.data.url".

https://github.com/angular/angular/issues/20956#issuecomment-374133852

like image 121
BolajiPemipo Avatar answered Sep 30 '22 08:09

BolajiPemipo