Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 firebase push notification is not working when application is in foreground

I'm following this document to implement the FCM on my Angular web application. When I send the notification it receives successfully when the application is not active. ( Recieve background notifications ). But if the application is active, I'm not getting the notification.

Following these steps: https://dev.to/mayurkadampro/angular-8-firebase-cloud-messaging-push-notifications-97a

basically this is not triggering when there is a new message

this.angularFireMessaging.messages.subscribe(
(payload) => {
    console.log("new message received. ", payload);
    this.currentMessage.next(payload);})

What Am I missing?

like image 313
user2609021 Avatar asked Feb 01 '20 16:02

user2609021


2 Answers

You need to trigger it manually.

When you receive you only logging it, and let the message go to the next one:

this.angularFireMessaging.messages.subscribe(
(payload) => {
    console.log("new message received. ", payload);
    this.currentMessage.next(payload);})

You need to trigger the notification from service worker:

this.angularFireMessaging.messages.subscribe(
(payload) => {
    console.log("new message received. ", payload);
    const NotificationOptions = {
            body: payload.notification.body,
            data: payload.data,
            icon: payload.notification.icon
          }
          navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
            registration.showNotification(payload.notification.title, NotificationOptions);
          });
    this.currentMessage.next(payload);})

Then add in firebase-messaging-sw.js:

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    event.waitUntil(self.clients.openWindow(event.notification.data.url));
});
like image 93
Mukyuu Avatar answered Oct 05 '22 19:10

Mukyuu


I've the same problem with my Vue.js application. It's still not clear to me how messaging service works but try to change the input payload. I suppose you are testing notifications using Postman.

Payload for foreground notifications:

{    
  "data":{ ..  },
  "to": "....",
}

Payload for background notifications:

{
  "notification": { ... },
  "to": ""
}
like image 25
matteogll Avatar answered Oct 05 '22 18:10

matteogll