Desperately need help for Firebase - Push Notifications

Hi guys,

I’m trying to develop Firebase - Push Notifications
I have installed the plugin by checking $ cordova plugin list
cordova-plugin-fcm 2.1.2 “FCMPlugin”
I have registered the app on the Firebase Console and have no idea whether this code is correct or not (it’s inside the app.js)

onDeviceReady: function() {
// JScript for the main app, once PGap has loaded.
//checkDeviceSize(); (WILL RE-CODE IN A CSS FRIENDLY FORMAT)
document.addEventListener(“offline”, onOffline, false);
document.addEventListener(“online”, onOnline, false);
setTimeout(function() {
navigator.splashscreen.hide();
}, 1000);

    var pushtoken;

    initFCM();
    getToken();
    
},

then, at the bottom of file app.js, I put the function

function initFCM() {
    console.log("initializing...");
    if(typeof(FCMPlugin) != 'undefined') {
     FCMPlugin.onTokenRefresh(function(token){
        pushtoken = token;
        app.dialog.alert('onTokenRefresh:', token);
     }, function(err){
        app.dialog.alert('error retrieving token: ' + err);
     });
     FCMPlugin.onNotification(function(data){
        if(data.wasTapped){
            app.dialog.alert(JSON.stringify(data));
        }else{
            app.dialog.alert(JSON.stringify(data));
        }
     }, function(msg){
        app.dialog.alert('onNotification callback successfully registered: ' + msg);
     }, function(err){
        app.dialog.alert('Error registering onNotification callback: ' + err);
     });
     }
}
function getToken() {
    if(typeof(FCMPlugin) != 'undefined') {
     FCMPlugin.getToken(function(token){
        pushtoken = token;
        app.dialog.alert('getToken:', token);
        if (!token) setTimeout(getToken, 1000);
     }, function(err){
        app.dialog.alert('error retrieving token: ' + err);
     });
    }
}

Would be very grateful if you can show how to manage this code inside app.js
Many thanks

Make sure that you have cordova.js loaded! otherwise it wont work,

Download both google-services.json for android and GoogleService-Info.plist from Firebase and include them in your project!

than this code is required for it to work, I use the Phongap Plugin Push

// Handle Cordova Device Ready Event
Dom7(document).on('deviceready', function() {

    var push = PushNotification.init({
        "android": {
            "senderID": "#####" // Enter your senderID
        },
         "ios": {
            "alert": true,
            "badge": true, 
            "vibration": true,
            "sound": true
        }, 
         "windows": {},
         "browser": {} 
    });

    push.on('registration', function(data) {
        var oldRegId = localStorage.getItem('registrationId');
        if (oldRegId !== data.registrationId) {
            // Save new registration ID
            localStorage.setItem('registrationId', data.registrationId);
            // Post registrationId to your app server as the value has changed
        }
        //gcm_id = data.registrationId;
        api.saveRegistrationId(data.registrationId, function(data) {
            data = JSON.parse(data);
            //console.log(data);
        });

    });

    push.on('notification', function(data) {
        //alert(data.title+" Message: " +data.message);
        // With callback on close
        var notificationCallbackOnClose = app.notification.create({
          icon: '<i class="fas fa-comments"></i>',
          title: data.title,
          titleRightText: 'now',
          text: data.message,
          closeOnClick: true,
          closeTimeout: 3000,
          on: {
            close: function () {
                //go to msg
            },
          },
        });
        notificationCallbackOnClose.open();
    });

    push.on('error', function(e) {
        console.log(e);
    });
});

This is all code you need for it to work.

all you have to do is to make some kind of API where you save the registrationId of everyuser
in my case i use the api.saveRegistrationId function

thanks for your reply. just wondering, where I can find cordova.js? it does not appear in project root folder.

cordova.js ist not in your project, you just have to add a line to include it in your index.html

<script type="text/javascript" src="cordova.js"></script>

but i cannot find the file cordova.js. do you think it just fine to attach cordova.js in index.html?

yes just add this line to index.html and you are fine

Thanks, I’ll try. However, you are using different plugin, right? Can we test it on simulator or is it just working in real device?

Hi, now I’m having another issue, getToken has return an empty string
Any ideas?

I am sorry but I dont use the FCM plugin

ok, thanks for all of your comment. Appreciate it!

I also used it with Phonegap Push Plugin with code similar posted by @Momo and hadn’t any issues

i decided to use Pushwoosh service and still having problem. Kindly check my latest question, please? Thanks a lot before.

use this

thanks, but I’ve done with Pushwoosh.

Phongap Plugin Push is depreciated, what code can i use.

Check that article

1 Like

I have followed the steps i didn’t get a push notification.

You have to change to Cordova App,. phonegap doesn’t exist anymore.

Check this plugins, i didn’t use, but give it a try.

Thanks this plugin worked but had this issues?

  • The push notification does not open if app is not on foreground/background mode.

  • Send a new notification dynamically.

that is the plugin I used! which is quite good and fast! can just recommend it!

function onDeviceReady() {
    document.addEventListener("resume", onResume.bind(this), false);
    document.addEventListener("active", onResume.bind(this), false);

    
    if(window.FCMPlugin) {
        //TODO differentiate between ios and android?
        window.FCMPlugin.hasPermission(function(check){
            if(check) {
                localStorage.setItem('hasPermissionNotify',0)
                window.FCMPlugin.subscribeToTopic('all');

                window.FCMPlugin.getToken(function(token){
                    if(token) {
                        localStorage.setItem('registrationId', token)
                        var obj = {
                            request : 'saveRegistrationId',
                            id: token,
                        };
                        getData(obj).then( function (response,status,xhr) {
                            //console.log(response)
                        }, function (response) {
                            //console.log("failed")
                        });
                    }
                });
                window.FCMPlugin.onTokenRefresh(function(token){
                    var oldRegId = localStorage.getItem('registrationId');
                    if (oldRegId !== token) {
                        if(token) {
                            localStorage.setItem('registrationId', token)
                            var obj = {
                                request : 'saveRegistrationId',
                                id: token,
                            };
                            getData(obj).then( function (response,status,xhr) {
                                //console.log(response)
                            }, function (response) {
                                //console.log("failed")
                            });
                        }
                    }
                });

                if (typeof window.FCMPlugin.clearAllNotifications === "function")
                    window.FCMPlugin.clearAllNotifications();

                window.FCMPlugin.onNotification(function (payload) {
                    window.notification_payload = payload;
                    if(window.notification_payload.wasTapped){

                        if (typeof window.FCMPlugin.clearAllNotifications === "function")
                            window.FCMPlugin.clearAllNotifications();
                        
                        window.notification_interval = window.setInterval(function() {
                            if (window.appReady) {
                                window.clearInterval(window.notification_interval);
                                if(window.notification_payload.tab)
                                    window.app.tab.show(window.notification_payload.tab)
                                else 
                                    window.app.tab.show('#view-main')
                                if(window.notification_payload.page)
                                    window.app.views.main.router.navigate(window.notification_payload.page)
                                
                                window.notification_payload = null;
                            }
                        }, 500);
                    } else {
                        app.emit('notificationRecieved', payload);
                    }
                });
            } else {
                localStorage.setItem('hasPermissionNotify',1)
            }
        });
    }
};
function onResume() {
    if(window.FCMPlugin) {
        if (typeof window.FCMPlugin.clearAllNotifications === "function")
            window.FCMPlugin.clearAllNotifications();
    }
    if(window.Keyboard) {
        window.Keyboard.hide();
    }
}

that’s all you need actually to make it work this is really specific code for one of my apps you should strip out what you dont need