Search code examples
firebaseionic-frameworkpush-notificationfirebase-cloud-messagingcapacitor

How can I access title and body data from pushNotificationActionPerformed into the ionic application with capacitor


I'm using Capacitor Push Notifications into my app. I've follow the capacitor tutorial from capacitor website, and implemented this code:

onPushNotifications() {
    // Register with Apple / Google to receive push via APNS/FCM
    PushNotifications.register();

    // On succcess, we should be able to receive notifications
    PushNotifications.addListener('registration', (token: PushNotificationToken) => {
      console.log('Push registration success, token: ' + token.value);
    });

    // Some issue with our setup and push will not work
    PushNotifications.addListener('registrationError', (error: any) => {
      console.log('Error on registration: ' + JSON.stringify(error));
      this.showToast('Erro ao ativar as notificações push.');
    });

    // Show us the notification payload if the app is open on our device
    PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => { 
      this.showToast(notification.title + '\n' + notification.body);
      this.addNewNotification(notification);
    });

    // Method called when tapping on a notification
    PushNotifications.addListener('pushNotificationActionPerformed', (notification: PushNotificationActionPerformed) => {
      this.addNewNotification(notification.notification.data); 
    });
  }

With this, I could access data title and body from push notification when the app is running in foreground (using pushNotificationReceived). But when the app is running in background I could access the title and body to save in an array, for exemple.

I tried implement this code:

// Method called when tapping on a notification
PushNotifications.addListener('pushNotificationActionPerformed',
      (notification: PushNotificationActionPerformed) => {
        let notif = this.state.notifications;
        notif.push({ id: notification.notification.data.id, title: notification.notification.data.title, body: notification.notification.data.body })
        this.setState({
          notifications: notif
        })
      }
    );

From this website https://medium.com/enappd/firebase-push-notification-in-ionic-react-app-using-capacitor-b6726c71bda4 But I got no functional answer. I keep getting undefined in title and body.

Please, can someone help me? Thanks!


Solution

  • Your payload should contain:

    • notification_foreground,
    • notification_title,
    • notification_body.

    You have to make:

    notification_foreground = true