In my Angular 14 Ionic 6 app I'm handling push notifications from Firebase:
import {ActionPerformed, PushNotifications, PushNotificationSchema, Token} from '@capacitor/push-notifications';
When the receiving app is in the background, the message is delivered to the tray, as expected.
However, when the app is in the foreground the notification message pops up - but I don't want it to show if the app is in foreground.
How can I bypass showing push notification when the app is in foreground?
Here's the cloud function that is pushing the notification:
//DB triggered function - A chat message from one party to the other
exports.sendChatMessage = functions.database.ref('/ChatMessages/{chat_message_id}')
.onCreate(async (snapshot, context) => {
const sendingRoleCode = snapshot.val().sendingRoleCode;
const senderId = snapshot.val().senderId;
const sessionId = snapshot.val().sessionId;
const receiverId = snapshot.val().receiverId;
const receiverDeviceId = snapshot.val().receiverDeviceId;
const timestamp = snapshot.val().timestamp;
const msgType = snapshot.val().msgType;
const senderImage = snapshot.val().senderImage;
const title = snapshot.val().title;
const body = snapshot.val().body;
let objData = {
sendingRoleCode: sendingRoleCode,
senderId: senderId,
sessionId: sessionId,
receiverId: receiverId,
receiverDeviceId: receiverDeviceId,
timestamp: timestamp,
msgType: msgType,
timestamp: timestamp,
notificationCode: "4"
}
//Notification payload
const payload = {
token: receiverDeviceId,
notification: {
"title": title,
"body": body,
"image": senderImage,
// click_action: 'com.skillblaster.app.helperinvitationnotification' //Tag associated with triggering an activity on the helper's app when background notification
},
data:{
data: JSON.stringify(objData)
},
android:{
"priority":"high",
"notification": {
"notification_priority": "PRIORITY_HIGH",
"default_vibrate_timings": true,
"default_light_settings": true,
}
},
apns:{
"headers":{
"apns-priority":"10"
},
payload: {
aps: {
'mutable-content': 1
}
},
fcm_options: {
image: senderImage
}
},
webpush: {
"headers": {
"Urgency": "high"
}
}
};
return admin.messaging().send(payload);
});
In my app, I have this (unused) handler, maybe I can use it to intercept the message and cancel its display by the OS?
PushNotifications.addListener(
'pushNotificationReceived',
async (notification: PushNotificationSchema) => {
const data = notification.data.data; //data.learnerId , data.notificationCode, ...
console.log('Push alert notification received: ' + JSON.stringify(notification));
//What to do next. Notification received on the device.
//alert('Push notification received: ' + notification);
//this.processNotificationReceived(JSON.parse(data), false); //All data processing is now done in the data notification section in fb-rtdb.service
});
This app is now tested on Android devices only, not yet on iOS.
Thanks!