UPDATE: This appears to be a bug in Android only, I finally tested things on my iOS devices and everything works as expected. When iOS app is open and a push notification message arrives, the onNotificationOpen fires and I am able to process the payload and create a custom message/popup to the user. This simply does not work in Android - onNotificationOpen never fires.
In the documentation for function onNotificationOpen, the author states:
App is in foreground:
User receives the notification data in the JavaScript callback without any notification on the device itself (this is the normal behaviour of push notifications, it is up to you, the developer, to notify the user)
But best I can tell, when the app is opened and a push is received, onNotificationOpen never fires, so the callback never fires.
window.FirebasePlugin.onNotificationOpen(function(payload) {
console.log(payload) ;
}, function(error) {
console.error(error);
}) ;
onNotificationOpen - if a payload exists, it gets processed as payload.ObjectKey - WORKSonNotificationOpen - DOES NOT WORK. console.log never fires (not even the error one), thus onNotificationOpen is not firing - this is contrary to author's documentation.So either its a bug OR the author somehow is referring to another JS callback in his documentation.
i think this is what you need: https://stackoverflow.com/questions/43928185/how-to-read-firebase-push-notification-content-and-fire-a-method-in-ionic2/43950976#43950976
tap which is part of the payload, will indicate if the app was in background/foreground mode when received
@jamesparkes
I am not using ionic2. However, I went through that stackoverflow, the first answer references using cordova-plugin-firebase and a repo that uses it. I combed over the repo and the only thing I found related to tap is this:
this.firebase.onNotificationOpen().subscribe(
(notification: NotificationModel) => {
!notification.tap
? console.log('The user was using the app when the notification arrived...')
: console.log('The app was closed when the notification arrived...');
let notificationAlert = this.alertCtrl.create({
title: notification.title,
message: notification.body,
buttons: ['Ok']
});
notificationAlert.present();
},
error => {
console.error('Error getting the notification', error);
});
Can this code somehow be used for a JS implementation in my own code? The tap part caught my eye...does window.FirebasePlugin.onNotificatinOpen(function(data) { ... } evaluate tap even if app is in the foreground? I had put simple console.log messages in the function assuming they would fire if the onNotificationOpen was even entered...but they and it never fired.
the end result is that onNotificationOpen does not fire if the app is already opened...so what method does? I can't seem to find one that does. In the orig documentation the author says "
Register notification callback:
window.FirebasePlugin.onNotificationOpen(function(notification) {
console.log(notification);
}, function(error) {
console.error(error);
});
Notification flow:
App is in foreground:
User receives the notification data in the JavaScript callback without any notification on the device itself (this is the normal behaviour of push notifications, it is up to you, the developer, to notify the user)
Yet provides no information on how to detect an incoming message if the app is already open...can't notify the user if I can't see how/where the notification is coming in. He indicates in the JS callback...but as best as I can tell, the callback never fires.
This probably won't be much help, but I was having the exact same problem. I just set up my Firebase account and started using this plugin and couldn't notifications when the app was open. Suddenly it just started working -- and now it works every time. I changed literally nothing. It seems like some information needed to get propagated through the system somewhere before everything would fully work.
Sorry this isn't much help, but if others are having the same problem maybe waiting an hour will help. It sounds stupid.. trust me.. I know.
so after working with this plugin last week, what is working for our project is...
google-services.json app file is in your project rootgoogle-services.json app file is placed in ./platforms/androidGoogleService-Info.plist app file is NOT in your project rootGoogleService-Info.plist app file in ./platforms/ios/[name-of-app]/Releases/@captainjim1 - can you post your code on how you are processing notification is the app is open and in the foreground? Everything else for me has been working properly except this one issue. App open in background - works. App closed - works. App open and foreground - onNotificationOpen is not firing.
@jamesparkes - yup...got all that in place, and I have push notifications working in all app states except when then app is open and in the foreground. Can you post your code on how to do this? I have read, am being told, that onNotificationOpen should execute when a notification arrives when the app is opened and in foreground, but I am putting in debug console.log messages just to see if the function fires and it never does.
If you all have it working then obviously its not a bug, but I can't see what I am doing wrong...why won't it fire if the app is opened in foreground, but will fire if app is closed or open and in the background?
sure thing. i'll post something here later this afternoon @rolinger
My working code isn't anything different than what is outlined in the Ionic docs. Like I said before, it just suddenly started working -- all of the time. The only thing I can think of is make sure that you're code that sets up the callback is being run when your app starts. At one point I had my init() function being called from ngOnInit() which doesn't work on Providers/Services. Moving the call to the constructor fixed that for me.
My app has a service to handle the notifications... I'll try to pare it down to the stuff you'd need..
import {Injectable} from "@angular/core";
import {Firebase} from "@ionic-native/firebase";
import {Platform} from "ionic-angular";
@Injectable()
export class NotificationService {
constructor(private platform: Platform,
private firebase: Firebase) {
this.init();
}
init() {
if (this.platform.is("cordova")) {
// save the token server-side and use it to push notifications to this device
this.firebase.getToken()
.then(token => console.log(`The token is ${token}`))
.catch(error => console.error("Error getting token", error));
this.firebase.onTokenRefresh()
.subscribe((token: string) => console.log(`Got a new token ${token}`));
// called when opening notification from the notif bar
this.firebase.onNotificationOpen()
.subscribe(data => {
this.receiveNotification(data);
},
err => {
console.log(err);
}
);
}
}
receiveNotification(firebaseNotif) {
// do somethign with your notification data here
}
initializeFirebase() {
if(!document.URL.startsWith('http')) {
// initialize push notifications
this.platform.is('android') ? this.initializeFirebaseAndroid() : this.initializeFirebaseIOS();
} else {
console.log('Push notifications are not enabled since this is not a real device');
}
}
private initializeFirebaseAndroid(): void {
this.firebase.getToken()
.catch((e) => {
console.error(e);
})
.then(token => {
console.log(`This Android device's token is ${token}`);
});
this.firebase.onTokenRefresh().subscribe((token: string) => {
// save device token
this.subscribeToPushNotifications();
}, e => {
console.error(e);
});
}
private initializeFirebaseIOS(): Promise<any> {
return this.firebase.grantPermission()
.catch((e) => {
console.error(e);
})
.then(() => {
this.firebase.getToken()
.catch((e) => {
console.error(e);
})
.then(token => {
console.log(`This iOS device's token is ${token}`);
});
this.firebase.onTokenRefresh().subscribe((token: string) => {
// save device token
this.subscribeToPushNotifications();
}, e => {
console.error(e);
});
});
}
private subscribeToPushNotifications() {
// handle incoming push notifications
this.firebase.onNotificationOpen().subscribe((pushNotification: Notification) => {
if (pushNotification.tap) {
// background received
} else {
// foreground received
}
}, e => {
console.error(e).
});
}
@captainjim1 @jamesparkes - both of your implementations are using onNotificationOpen().subscribe()
At the moment I am simply just trying to get the basic one working while app is open. My implementation is just for basic push notifications. I don't have any subscription based notifications, nothing the user is or needs to specifically subscribe too. I don't think this should be affecting my implementation though as I know my app is still getting them and processing them when the app is closed or open and in the background.
I think you're misunderstanding what's happening with the "subscribe" call.
this.firebase.onNotificationOpen() return an Rxjs observable object. In order for an observer (your app) to see the items being emitted by an Observable it must first subscribe to that Observable with this operator.
Failing to subscribe to the onNotificationOpen() observable means your app is never doing anything when a notification is opened. This has nothing to do with subscribing to more specific types of notifications.
@captainjim1, @jamesparkes - I guess I don't understand your implementation of of subscribe() then. According to the plugin docs (and my understanding of them), subscribe('topicA') is specifically looking for notifications for a topicA channel/thread....but if not used, then its just a standard push notification. Or am I not understanding this correctly? For my app, I am not using any specific topics/channels that a user would need to specifically subscribe to. That being said, I am posting all of my code below:
Maybe you can see where I am going wrong...cause I sure as heck can't.
/// new firebase/push load
function writeToken(token) {
var oldToken = getDB("dev_pushID") ;
if (oldToken != token) {
setDB("dev_pushID",token,1) ; // writes the token to local DB
// apiService sends the specific user info & token to my app server
apiService.all("PUT",[{table:"userDevice","sid":"user_ID","sidValue":userData.user_ID}]) ;
}
}
// check to see if grantPermissions have changed
// iOS grantPermission takes place in another section of the app during 1st time app initialization
window.FirebasePlugin.hasPermission(function(data){
var oldPushEnabled = Number(getDB('dev_pushEnabled')) ;
console.log("hasPermission = " +oldPushEnabled) ;
if (data.isEnabled != oldPushEnabled) {
setDB('dev_pushEnabled',pushIsEnabled,1) ; // set local app db value
apiService.all("PUT",[{table:"userDevice","sid":"user_ID","sidValue":userData.user_ID}]) ;
}
if (data.isEnabled == oldPushEnabled) {
console.log("Old & New Match") ;
}
});
// get new token if one doesn't exist
window.FirebasePlugin.getToken(function(token) {
writeToken(token)
});
// look for new token to see if it has changed
window.FirebasePlugin.onTokenRefresh(function(token) {
writeToken(token) ;
}, function(error) {
console.error(error);
});
// The below function works for open in background, works if app is closed
// but does not work if app is open and in foreground
// IF no payload, then its a standard push notification
// my understanding is if app is open in foreground, the only way to process any message
// info is if it exists in the payload. (regardless, this function never fires anyway).
window.FirebasePlugin.onNotificationOpen(function(payload) {
// console.log("Tap is: " +payload.tap) ;
// if there is a payload it will be in payload object
if (payload.action == 1) { // email verification confirmation
setDB("user_emailVerify",payload.user_emailVerify) ;
} else if (payload.action == 2) {
alert(payload.dataTitle+ "\n" +payload.dataMsg) ;
}
}, function(error) {
console.error(error);
}) ;
// The above prints out the console.log message when :
// 1. app is closed, msg arrives, user taps msg and opens app
// 2. app is open in back ground, msg arrives, user taps msg and opens app
//But the above console.log msg never prints out when msg arrives while app is open in foreground.
//This tells me that onNotificationOpen() never fires when app is open in foreground
There are TWO different subscribe functions at play here. The window.FirebasePlugin.subscribe function is not needed to receive generic notifications like you wish. That function is different than this.firebase.onNotificationOpen().subscribe().
this.firebase.onNotificationOpen() returns an Rxjs Observable object. The .subscribe() call you need is a method that belongs to the Observable class. Observables are something that is totally independant from this plugin. Google "rxjs observable" and you'll see there's a lot out there about them. They are similar to Promises, but more powerful.
Remember, different object types can have methods with the same name, that do totally different things.
Another way to think about this would be if we wrote code like this.
const myNotificationHandler = this.firebase.onNotificationOpen();
... this creates myNotificationHandler as an Observable type.
myNotificationHandler.subscribe( incomingNotification=> {
// do something with a notification
});
.... this makes your app start listening for notifications -- you're _subscribing_ to the observable and arrow the function inside the subscribe method is what you do when you get a notification. Again, this is totally separate from the subscribe() method that exists in the FirebasePlugin object.
Your best bet would be to try our sample code and see if it works for you. The implementation we've provided is simple enough to work into your code (or test it independently). In the end you'll probably save time by simply trying our code out and seeing if it works for you.
@captainjim1 - thanks for the explanation. I am going to be reading up on Rxjs Observable objects today and trying to implement the code the way you two have done it. I guess the thing that throws me, that makes me believe there is an Android bug, is that the above code I posted ALL works on iPhone; this includes properly receiving and processing notifications while the app is open and in foreground.
So why does it work on iPhone and not Android for open/foreground notifications? why would I have to modify my code for google's Android when in fact the whole plugin is based on google firebase?
This is/has been quite frustrating. ugh!
The fact that it's working for me and @jamesparkes on Android should tell you it's not an Android bug. I don't see it, but you probably have a small quirk somewhere in your code that is letting it work on iOS when it shouldn't. If anything, there might be a bug in the iOS version of the plugin that's allowing you to get away with not subscribing to the onNotificationReceived() Observable.
I hope it works out - report back!
heh...interesting....a bug that allows something to work. That one def never occurred to me. Should be testing things today, will post back later.
@captainjim1 @jamesparkes @apptum - well...no luck. I have tried 10 more methods and still can't get notifications when the app is open/foreground. I went through Ionic directions and read in quite a few other places - nothing is working. I have gotten so far off track that I just want to get this back to the basic Javascript plugin.
Does ANYONE have it working in native javascript? As the author writes:
onNotificationOpen
Register notification callback:
window.FirebasePlugin.onNotificationOpen(function(notification) {
// open/foreground - message arrives, no status bar icon, console.log should fire, but does not.
console.log(notification);
// closed/background - message arrives, status bar icon appears, console.log does fire
}, function(error) {
console.error(error);
});
Notification flow:
@captainjim1 - ok...way back on Aug 8th or so (22 days ago) you mention that it all suddenly just started working for you. Well, I got so frustrated with this plugin that I decided to just forgo trying to get Notifications while app is open and in foreground. I couldn't delay my next app release any longer, so I compiled my app to submit to Android Play Store and then forked my project into a new development version.
During compiling of the new development version I had a FirebaseCrash.class warning that I hadn't seen before...but the compile didn't fail. I launched the new development version to my Android phone and decided to test Firebase components to see if that warning was going to cause any problems....I closed the app and sent a Firebase Notification - worked as expected. Then I opened the app and sent another notification to test if the app would crash when a notification arrived (as I had seen that before)....not only did it not crash, but also my console.log/alert messages all fired (that ONE thing I couldn't get it to do these last 30 days!!!!!!!!!!).
I did nothing...I didn't change or edit any code...I simply just forked the project and recompiled the new development version - and waaaalaaaaa - Notifications were getting received while the app was open and in the foreground. Are you f'n kidding me!!!!! 30 days trying to get the damn open/foreground thing to work and simply forking the project got it to work. GGGGrrrrrrrr!
Now I am going to submit this new development version to the app stores (cause I know this one now works)...and then fork it again to continue developing. Unreal!
Hello @rolinger :)
I have some issue with onNotificationOpen but the diferent is iam sending the notification from firebase console with a parameters, I use that parameter to navégate in the app when the notification is open for some reason when the app is open and I send a notification the onNotificationOpen fires Well, when the app is close th notification arrived when I tab to open the notification the onNotificationOpen is not fire.
Hello,
I'm facing with the same issue . onNotificationOpen is not fire when the app is open/foreground on Android.
Is there any available solution ?
No idea.... no answer.
Sent from my iPhone
On Apr 3, 2018, at 11:33 PM, reydajp notifications@github.com wrote:
Hello,
I'm facing with the same issue . onNotificationOpen is not fire when the app is open/foreground on Android.
Is there any available solution ?—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.
Hello
I have partialy the same issue.
when the app is closed, I receive the notification.
But when the app open the onNotificationOpen event don't fire
On iOS everything is OK ( foreground and background)
On Android it's OK only when the App is closed. And when I tape on the notification it's launch the app.
But when the App is open, I don't receive the notification.
Is there any available solution ?
thank you
Hi!
Any updates?
Android notifications(foreground mode) doesn't work for me also.
Background mode - everything is OK.
iOS - also is works good for both mode.
Hi,
Unfortunately no update.
it's seem to be normal on Android. the concept of notification is not the
same as iOS.
There two kind of message event.
Now I use well cordova-plugin-frm for iOS and Android.
This plugin strap all event forground and background.
Regards
2018-06-29 9:30 GMT+02:00 Fikret Kurtiev notifications@github.com:
Hi!
Any updates?
Android notifications(foreground mode) doesn't work for me also.
Background mode - everything is OK.
iOS - also is works good for both mode.—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/arnesson/cordova-plugin-firebase/issues/371#issuecomment-401272715,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AhQFU5eIRyISrYhQeJNfDD1grcWTxANAks5uBdebgaJpZM4Osf2U
.
hello.
I have solved this problem with _Fixing a Cordova Android Emulator Bug_, maybe it can be helpful.
As of March 2018, there’s a bug in the cordova Android emulator code, but it can be fixed by updating a single line of code, which I learned form this Ionic forum response.
Open /platforms/android/cordova/lib/emulator.js and find this line:
var num = target.split(’(API level ‘)[1].replace(’)’, ‘’);Then replace it with this line:
var num = target.match(/\d+/)[0];
the same issue. any solution yet?
hi, still I am facing this issue in ionic 4. when app in foreground state Onnotification() does not trigger. could you please any one give me solutions...
Hy
I don't find solution.
Finaly to be compatible with iOS and Android I use an other plugin :
cordova-plugin-fcm
Best regards
David
Le lun. 17 févr. 2020 à 11:02, sachinbp589 notifications@github.com a
écrit :
hi, still I am facing this issue in ionic 4. when app in foreground state
Onnotification() does not trigger. could you please any one give me
solutions...—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/arnesson/cordova-plugin-firebase/issues/371?email_source=notifications&email_token=AIKAKU54YNEJURXXEFARNTLRDJOEXA5CNFSM4DVR7WKKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEL5ZBGY#issuecomment-586911899,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AIKAKU4WVVHBHYZVCPT3T3LRDJOEXANCNFSM4DVR7WKA
.
hi, I am also using cordova-plugin-fcm, but its not working .
-> ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated
-> npm install @ionic-native/fcm
could you please give me which plugin are you using.
Hi, Also please refere below link-
https://stackoverflow.com/questions/60225787/firebase-onnotification-is-not-working-when-the-notification-is-received-in-an
I use old version
cordova-support-google-services 1.2.0
cordova-plugin-fcm 2.1.2
I don"t use ionic framework but full javascript project
SAILLARD David
Chef de projet sénior
*Société *DANEM, Zone d'activités Europarc - 40, Rue Eugène Dupuis - 94044
Créteil cedex
*Email * [email protected] Somnter94@gmail.com *Web *www.danem.com
Zone d'activités Europarc https://goo.gl/maps/RP12D40 rue Eugène Dupuis
94000 CRETEIL https://goo.gl/maps/RP12D
Tel : 01 41 94 10 80
https://www.danem.com http://www.danem.com/
Le lun. 17 févr. 2020 à 12:11, sachinbp589 notifications@github.com a
écrit :
hi, I am also using cordova-plugin-fcm, but its not working .
-> ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated
-> npm install @ionic-native/fcmcould you please give me which plugin are you using.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/arnesson/cordova-plugin-firebase/issues/371?email_source=notifications&email_token=AIKAKU4NBGYOVWRJKRCCLYLRDJWHRA5CNFSM4DVR7WKKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEL6AW5Y#issuecomment-586943351,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AIKAKU5WR2TCLAQWXOHBGWTRDJWHRANCNFSM4DVR7WKA
.
Most helpful comment