6

I have configured web push notifications to my PWA ionic 4 app. The web push notifications are working like a charm when the tab is switched i.e in background or other than my app.

The issue is when the tab is active I get the push messaging inside application section of chrome inspection but there is no notification fired.

Below is the code:

app.component.ts

async ngOnInit() {
firebase.initializeApp(environment.firebase);
}

ngAfterViewInit() {
   this.platform.ready().then(async () => {
   await this.notificationsService.requestPermission();
   });
}

notifications.service.ts

export class NotificationsService {
  init(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      navigator.serviceWorker.ready.then(
    registration => {
      // Don't crash an error if messaging not supported
      if (!firebase.messaging.isSupported()) {
        resolve();
        return;
      }

      const messaging = firebase.messaging();

      // Register the Service Worker
      messaging.useServiceWorker(registration);

      // Initialize your VAPI key
      messaging.usePublicVapidKey(environment.firebase.vapidKey);


      // Listen to messages when your app is in the foreground
      messaging.onMessage(payload => {
        console.log("Payload is here", payload);
      });
      // Optional and not covered in the article
      // Handle token refresh
      messaging.onTokenRefresh(() => {
        messaging
          .getToken()
          .then((refreshedToken: string) => {
            console.log(refreshedToken);
          })
          .catch(err => {
            console.error(err);
          });
      });

      resolve();
    },
    err => {
      reject(err);
    }
  );
});
}

So when notificatoin is triggered if the application tab is open in chrome is should call console.log inside messaging.onMessage but it doesn't get executed. I am using firebase version of 7.8.0 in firebase-messaging-sw.js.

Abid Iqbal
  • 753
  • 8
  • 22

1 Answers1

-1

When your application in Foreground, your app will not going to receive notification with messaging observable but it will be emitted on messages observable.

So you should subscribe it like this

firebase.messages.subscribe((message: any) => {
        if (message.notification) {
          // Show your notification from here
        }
      });
Kathak Dabhi
  • 399
  • 3
  • 16