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

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!

Your payload should contain:
notification_foreground,
notification_title,
notification_body.
You have to make:
notification_foreground = true

Sadly that’s how push with notification payload work, when in background or closed the OS handles them, using the title and body to display the notification in the tray, but when you tap them, that information is no longer available for the app.
Use data payload to pass any data you want.

Related

PWA listen for event upon receiving push notification (while app is not running)

I'm trying to get the data that i receive from my push notification and display it in the pwa. The idea is that i have a push notification coming in with a text body, then the user clicks on the push notification and the PWA opens up with the data from the push notification displayed on the section. I have managed to get it work when it is open as i placed it in the mounted lifecycle and the function activates when it listens to the message that comes in. The only problem is when the push notification comes in, the user will not be having the PWA all the way. So how do i overcome this? I have tried inserting in other lifecycle methods but it seems redundant since the PWA is not even opened yet when the push notification arrives. Hope anyone here can advise on this. Thank you very much.
mounted(){
navigator.serviceWorker.addEventListener('message', (e) => {
console.log('Push Notification received');
console.log(e.data.firebaseMessagingData.notification.body);
var timestamp = new Date().toLocaleTimeString(undefined, {hour: '2-digit', minute: '2-digit'});
const robotMessage = {
text: e.data.firebaseMessagingData.notification.body,
isRobot: true,
timestamp: timestamp
}
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.collection("messages")
.add({
robotMessage: robotMessage.text,
timestamp: robotMessage.timestamp
});
this.messages.push(robotMessage);
});
}

Push Notifications in Perl

I am implementing push notifications for a site that has a Perl back end. Firebase is the push notification service i am using. I have spent a fair bit of time with this and looked at a number of guides and some useful resources on SO. I have come up with a working implementation with just one issue. The problem is when send out a push notification it seems to arrive on the client/browser as an empty message. That is no data containing the 'title' and 'body' is retrievable on the client/browser side when the push notification arrives.
I have tried using both firebases older and newer api and either way it ends up with the same outcome of empty push notifications arriving on the client/browser. I have tested this on chrome,firefox and android and the same thing happens.
Here is the perl code that sends the push notification. I have excluded generating the bearer token to limit how much code there is to read.
#SEND PUSH NOTIFICATION
my $push_subscriber = <get subscriber details from db>
my $end_point_host = $push_subscriber->{endpoint};
my $end_point = "https://$end_point_host/v1/projects/<my project
id>/messages:send";
my $request = HTTP::Request->new('POST',$end_point);
$request->header('Authorization'=>"Bearer $bearer_token");
$request->header('Content-Type' => 'application/json');
$request->content(JSON::encode_json ({
message => {
token => $push_subscriber->{subscription_id},
notification => {
title => 'test',
body => 'test content'
},
webpush => {
headers => {
Urgency => 'high'
},
notification => {
body => 'test content',
requireInteraction => 'true'
}
}
}}));
#send the request
$ua->request($request));
Here is the client/browser side javascript that is called when a push notification arrives. This is inside service-worker.js
self.addEventListener('push', function(e) {
var body;
if (e.data) {//THE PROBLEM IS HERE. No 'data' object exists
body = e.data.text();
} else {
body = "Empty Message";
}
var options = {
body: body
};
e.waitUntil(
self.registration.showNotification('My Notification', options)
);
});
The point where the problem presents itself is pointed out in the above javascript. Any help/feedback would be much appreciated. Thanks.
I ended up getting this working by just re-writing my client side subscription code. In my case the bell icon subscription on/off button along with all the js code to make it work.
Basically i went from using googles solution to a firebase specific solution with this guide.
https://firebase.google.com/docs/cloud-messaging/js/receive
You only need to store the 'token' on your server and the endpoint is always - https://fcm.googleapis.com/v1/projects/YOUR PROJECT ID/messages:send
The firebase guide contains a sample file where you can subscribe/unsubscribe for push notifications.
https://github.com/firebase/quickstart-js/blob/4be200b1c55616535159365b74bfd1fc128c1ebf/messaging/index.html
Once i had this working i could then cut it down and re-write it into just a simple notification button.
For some reason the provided firebase-messaging-sw.js from the guide didn't work for me but using service-worker.js shown in my OP did and so i can now receive push notifications along with their title, body and other data.
This here is how i generate the bearer token used in my OP sample perl code to send out a push notification.
Google API OAuth2 : “invalid_grant” error when requesting token for Service Account with Perl
That should hopefully cover everything you need to know if you are wanting to do push notifications on a site with a Perl back end. Hopefully this helps someone else wanting to do the same thing.

React Native: managing notification on RNFirebase

I have successfully implemented a basic notification feature using react-native-firebase library, everything is working as expected, information is properly received and ready to be used for a purpose I have yet to determine. My code currently look like this for the notification handling part:
componentDidMount() {
/**
* When app on foreground, rewrap received notification and re-send it as notification using channelId
* A workaround because channelId never set by default by FCM API so we need to rewrap to make sure it is
* shown on user's notification tray
*/
this.notificationListener = firebase.notifications().onNotification((notification) => {
//data object must have channelId props as a workaround for foreground notification on Android
console.log('Notif ', notification);
notification.android.setChannelId(notification.data.channelId);
firebase.notifications().displayNotification(notification);
});
//On Notification tapped, be it from foreground or background
this.notificationOpen = firebase.notifications().onNotificationOpened((notificationOpen) => {
//body and title lost if accessed from background, taking info from data object by default
const notification = notificationOpen.notification;
console.log('Open ', notification)
Alert.alert(notification.data.title, notification.data.body);
});
//When notification received when app is closed
this.initialNotification = firebase.notifications().getInitialNotification()
.then((notificationOpen) => {
//body and title lost if accessed this way, taking info from data object where info will persist
if (notificationOpen) {
const notification = notificationOpen.notification;
console.log('Initial ', notification)
Alert.alert(notification.data.title, notification.data.body);
}
});
}
componentWillUnmount() {
this.notificationListener();
this.initialNotification()
this.notificationOpen();
}
The above code let me use any information I sent from firebase console or a php server set up by my colleague from within the above scope (not sure how the server side implementation was done, but it gives me the exact same notification object on my end).
So that's good and all, but the problem is when I set badge on IOS from firebase console, the badge doesn't go away once I opened the notification.
I have been trying to figure out if there's any extra bit I have to add to the above block to programatically decrement the badge counter, but have no luck so far.
So if anyone here can show me how to manage these notification objects properly (especially explaining the nature and lifecycle of these objects -- i.e. which data on which property/method persists or is static within the scope of the notification object) on both Android and IOS, that would be greatly appreciated :)
Turns out a simple firebase.notifications().setBadge(0) on root componentDidMount() clears out the badge count whenever the app is opened.
May need to use firebase.notifications().removeAllDeliveredNotifications() or firebase.notifications().cancelAllNotifications() to remove them from notification tray too.
May be you have to set code for badge while creating a notification
this.notificationListener = firebase.notifications().onNotification((notification) => {
const localNotification = new firebase.notifications.Notification()
.setNotificationId(notification.notificationId)
.setTitle(notification.title)
.setSubtitle(notification.subtitle)
.setBody(notification.body)
.setData(notification.data)
.ios.setBadge(notification.ios.badge);
firebase.notifications()
.displayNotification(localNotification)
.catch(err => console.error(err));
}
Put this line in code .ios.setBadge(notification.ios.badge); while building a notification and try again

Custom click on Ionic notification using Firebase

I have been using ionic and FCM (Firebase Cloud Messaging) for notification.
I get the notification on my app and now I have 2 issues. First, if its a normal notification like not with advanced options in Firebase Console > Notification, then it doesn't play any sound, but when it's data Notification, then it does play a sound. Second, I want to open a particular page of my app on notification click.
So how do I do that?
Note: I am using ionic not an ionic2.
First issue:
We have sound in both situations. Have you tried to send an empty data object?
Second issue:
Just assuming you use the Cordova FCM plugin. Otherwise install it with
cordova plugin add cordova-plugin-fcm --save
Use the data with an ID to the right datapage and then do something like:
angular.module('app', ['ionic'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova) {
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
$state.go('yourpage', {id:data.pageId});
console.log('onNotification tapped true');
} else {
//Notification was received in foreground. User needs to be notified.
console.log('onNotification tapped false');
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
}
});
});

push not initilizing when trying to create hybrid android application

I am trying to implement push notifications using bluemix and mobilefirst. I have used the following links to implement
http://www.ibm.com/developerworks/library/mo-cordova-push-app/
http://mbaas-gettingstarted.ng.bluemix.net/hybrid#initialize-push -
When i run the the below code I am getting the following message in the console:
initPush called----------------
main.js:29 calling bluemix initialize with values----------------------
IBMBluemixHybrid.js:2956 [INFO] [DEFAULT] Hybrid initialize ["applicationid","applicationsecret","applicationroute"]
I neither see the device details reflected in the bluemix registered list. Can you please help me on this ?
var values = {
applicationId:"applicationId",
applicationRoute:"applicationRoute",
applicationSecret:"applicationSecret"
};
console.log("initPush called---------------------------------");
console.log("calling bluemix initialize with values--------------------------------");
IBMBluemix.initialize(values).then(function(status) {
console.log("IBM Bluemix Initialized", status);
return IBMPush.initializeService();
}, function (err) {
console.error("IBM Bluemix initialized failed" , err);
}).then(function(pushObj) {
function pushReceived(info) {
console.log("registerListener - " + info.alert);
alert('got a push message! ' + info.alert);
}
console.log("IBM Push Initialized", pushObj);
push = pushObj;
return push.registerDevice("LisaTest","Lisa123","pushReceived");
}, function (err) {
console.error("IBM Bluemix Push initialized failed" , err);
});
You need to replace "applicationId", "applicationRoute", and "applicationSecret" in the code
var values = {
applicationId:"applicationId",
applicationRoute:"applicationRoute",
applicationSecret:"applicationSecret"
};
with those obtained from your Bluemix backend application.
From the bluemix dashboard for your application click mobile options in the top right to see your ID and Route.
For the secret navigate to the Mobile Application Security dashboard from the link on the right, and your secret will be displayed on that page.

Resources