How to control when to ask for notification permission with FCM plugin

I am using FCM plugin for notifications. I would like to ask for notification permission when my users click a button within the app.

But, now the app asks for notification on launch. I’d rather ask for notifications later. Not right away.

I am using the FCM plugin only in app.component.ts. I made the FCM plugin code to start running on the condition that a database variable exists and equals to a certain value. This value is changed in the app when the user clicks a button. I was hoping the the plugin would kick in when the button is clicked but not when the app starts. Here is my code. Please help! :slight_smile:

 platform.ready().then(() => {

//START: notification operator    
const authListener=afAuth.authState.subscribe(user =>  {
if (user) {
this.userId = user.uid;
//check if user answered yes to the question asked after first clicking a follow button
firebase.database().ref(`/members/${this.userId}/notStats/`).on("value", res => {
if (res.exists()) {
if (res.val().notifAllowed == true ) {
//START: get device token and save in user members
fcm.getToken().then(token => {
   afDatabase.object(`/members/${this.userId}/notificationStatus/`).update({deviceToken: token});
});
//START: subscribe to notification listener
fcm.onNotification().subscribe(data => {
if (data.wasTapped) {//Notification tapped by the user 
  console.log(JSON.stringify(data));
} else { //App was in foreground when notification was sent
  console.log(JSON.stringify(data));}
});
} //end: if notifsAllowed saved in database as true
} //end: if exists
});//end: firebase listener   
authListener.unsubscribe();} else {authListener.unsubscribe();}});
//notification operator: END

});

How can I get FCM to ask for notification permission when the button in the app is first clicked? I do not wish the app to ask for permission to send notifications on first download. It makes for terrible user experience, asking for permission at the beginning before users even get to see the app.

Thanks!

2 Likes

I switched over to the Firebase Messaging plugin for this reason - https://ionicframework.com/docs/native/firebase-messaging