Search code examples
angularfirebasepush-notificationprogressive-web-appscapacitor

How to get Angular Push Notification in Android Native App using Capacitor?


I'm developing Angular progressive web application, when I run the application using ng serve it's working well in browsers with background notifications on service worker.

But the same functionality is not working with mobile application which is created with Capacitor build tools using npx cap add android.

My firebase-service-worker.js file :

importScripts('https://www.gstatic.com/firebasejs/5.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.5.0/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': '65358642427'
});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {

  var notificationTitle = JSON.parse(payload.notification).title;
  var notificationOptions = {
    body: JSON.parse(payload.notification).body
  };

  return self.registration.showNotification(notificationTitle, notificationOptions);
});

Solution

  • For the purposes of registering and monitoring in background for push notifications from Firebase Angular APP, Use the Push Notification API for Capacitor in an Ionic + Angular application.

    1. Prepare your Firebase account and create Android application in Firebase console with a package ID, example package : com.example.myapp
    2. Download the google-services.json file from Firebase console and paste it to your project root directory.
    3. Create Android project in your directory using capacitor : npx cap add android

    Finally handle the notification listener in your app component.

    import { Component, OnInit } from '@angular/core';
    
    import {
      Plugins,
      PushNotification,
      PushNotificationToken,
      PushNotificationActionPerformed } from '@capacitor/core';
    
    const { PushNotifications } = Plugins;
    
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.scss'],
    })
    
    export class HomePage implements OnInit {
    
      ngOnInit() {
        console.log('Initializing HomePage');
    
        PushNotifications.register();
    
        PushNotifications.addListener('registration', 
          (token: PushNotificationToken) => {
            alert('Push registration success, token: ' + token.value);
          }
        );
    
        PushNotifications.addListener('registrationError', 
          (error: any) => {
            alert('Error on registration: ' + JSON.stringify(error));
          }
        );
    
        PushNotifications.addListener('pushNotificationReceived', 
          (notification: PushNotification) => {
            alert('Push received: ' + JSON.stringify(notification));
          }
        );
    
        PushNotifications.addListener('pushNotificationActionPerformed', 
          (notification: PushNotificationActionPerformed) => {
            alert('Push action performed: ' + JSON.stringify(notification));
          }
        );
    }
    

    Note : When you receive a notification from Firebase this app will not be triggred but the pushNotificationActionPerformed will be triggred when you click the notification and redirected to APP.

    https://capacitor.ionicframework.com/docs/apis/push-notifications