Cordova Push Notifications (PhoneGap PushPlugin) not firing ecb callback (onNotificationAPN)
Asked Answered
R

3

8

I'm using the Cordova Push Notifications Plugin 1.3.4 with my Cordova/Phonegap App. Unfortunately, when receiving a push notification, the ecb callback in my JavaScript is never fired and I can't handle the push notification (not even when the app is running in foreground).

I'm using the example code from the demo:

pushNotification.register(tokenHandler, errorHandler, {"badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN"});

The registration is successful, but the following callback is never triggered:

function onNotificationAPN (event) {
    if (event.alert)
    {
        navigator.notification.alert(event.alert);
    }
 }
River answered 3/4, 2014 at 23:19 Comment(0)
R
9

The problem is the way you defined your callback function, causing the Push Plugin's evaluation of your callback (i.e., via [webView stringByEvaluatingJavaScriptFromString) to fail, since it will not be aware of it.

If you define your callback function as a global object instead, the plugin will trigger your callback correctly every time a new notification arrives:

onNotificationAPN = function(event) {
    if (event.alert)
    {
        navigator.notification.alert(event.alert);
    };
};

For Android, you'd define your onNotificationGCM callback the same way.

River answered 3/4, 2014 at 23:19 Comment(7)
Not sure what you mean by "parse time definition". onNotificationAPN has to be defined globally since that is the context stringByEvaluatingJavaScriptFromString evaluates javascript in.Amen
yeah right, that's what I meant. I like the way you put it, +1 on thatRiver
It actually makes no sense whatever you wrote. I had to decipher what you said and then @Amen said that id had to be defined globally. Finally, got my device to register. Thanks!Silk
thank you for rescuing my 2 hours search of the error and resolving this issue for me!!Clunk
I have been working on this all day, thank you so much!Gynecic
Define the function on window explicitly instead of an implicit global: window.onNotificationAPN = function(event)...Target
This solution is not working for me. I've already defined onNotificationAPN function globaly attached with window object like this window.onNotificationAPN = function(event){ console.log(event)} so that the plug-in can find the function easily. But still ecb isn't calling this function.Monometallism
F
2

Mobiletainment's answer fixed it for me! I've been searching all afternoon for the solution to this, albeit for the GCM callback, but the functionality is the same.

I'd upvote Mobiletainment, but I'm new here and it won't let me, but thanks!

For anyone that may be searching for a GCM solution (which there are many in the Googleverse without many good answers) here was my code that finally worked:

// handle GCM notifications for Android 
            onNotificationGCM = function(e){
                alert('onGCM');
                switch( e.event )
                {
                    case 'registered':
                        if ( e.regid.length > 0 )
                        {
                            console.log("Regid " + e.regid);
                            //Do registration work here...
                        }
                    break;

                    case 'message':
                      // this is the actual push notification. its format depends on the data model from the push server
                      alert('message = '+e.message+' msgcnt = '+e.msgcnt);
                    break;

                    case 'error':
                      alert('GCM error = '+e.msg);
                    break;

                    default:
                      alert('An unknown GCM event has occurred');
                      break;
                }
            }     
Fermata answered 8/9, 2014 at 21:49 Comment(0)
M
1

If you are using with azure push..below is the working code.(pushplugin for phonegap)

    function InitpushNotificaions() {
      //  alert("Notification setup");
        try {


            mobileServiceClient = new WindowsAzure.MobileServiceClient('https://mobbacktest.azure-mobile.net/', 'RvahPxHKoEsGiLdlCYZpHBllvSVQxl66');
            pushNotification = window.plugins.pushNotification;
            if (device.platform == 'android' || device.platform == 'Android' ||
                    device.platform == 'amazon-fireos')
            {
                // AndroId

                pushNotification.register(successHandler, errorHandler, { "senderID": "724086851305", "ecb": "onNotification" });       // required!
            }
            else
            {
                //IOS
                pushNotification.register(tokenHandler, errorHandler, { "badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN" });   // required!
            }
        }
        catch (err) {
            txt = "There was an error on this page.\n\n";
            txt += "Error description: " + err.message + "\n\n";
            alert(txt);
        }




    }


    // handle APNS notifications for iOS
 onNotificationAPN=function (e) {
        if (e.alert) {
            $("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
            // showing an alert also requires the org.apache.cordova.dialogs plugin
            navigator.notification.alert(e.alert);
        }

        if (e.sound) {
            // playing a sound also requires the org.apache.cordova.media plugin
            var snd = new Media(e.sound);
            snd.play();
        }

        if (e.badge) {
            pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
        }
    }

    //handle GCM notifications for Android
    onNotification = function (e) {
       // alert("gcm");
        switch (e.event) {
            case 'registered':
                if (e.regid.length > 0) {
                    // Your GCM push server needs to know the regID before it can push to this device
                    // here is where you might want to send it the regID for later use.
                   // alert('step 1 Azure! ' + e.regid);
                    if (mobileServiceClient) {
                       // alert('step 2 Azure!');
                        // Template registration.
                        var template = "{ \"data\" : {\"message\":\"$(message)\"}}";
                        // Register for notifications.
                        mobileServiceClient.push.gcm.registerTemplate(e.regid,
                          "myTemplate", template, null)
                          .done(function () {
                           //   alert('Registered template with Azure!');
                          }).fail(function (error) {
                              //alert('Failed registering with Azure: ' + error);
                          });
                    }



                    console.log("regID = " + e.regid);
                }
                break;

            case 'message':
                // if this flag is set, this notification happened while we were in the foreground.
                // you might want to play a sound to get the user's attention, throw up a dialog, etc.
                if (e.foreground) {

                    // on Android soundname is outside the payload. 
                    // On Amazon FireOS all custom attributes are contained within payload
                    var soundfile = e.soundname || e.payload.sound;
                    // if the notification contains a soundname, play it.
                    // playing a sound also requires the org.apache.cordova.media plugin
                    var my_media = new Media("/res/" + beep.wav);
                    alert("Message:"+e.message);
                    my_media.play();
                }
                else {  // otherwise we were launched because the user touched a notification in the notification tray.
                    if (e.coldstart) {

                    }
                    else {

                    }
                }


                break;

            case 'error':
                break;

            default:
                break;
        }
    }


    function tokenHandler(result)
    {
       // $("#app-status-ul").append('<li>token: '+ result +'</li>');
        // Your iOS push server needs to know the token before it can push to this device
        // here is where you might want to send it the token for later use.
    }

    function successHandler(result) {
        alert("Success handler:" + result);
     //   $("#app-status-ul").append('<li>success:'+ result +'</li>');
    }

    function errorHandler(error) {
        alert("Error handler:" + error);
    }
Magenmagena answered 22/10, 2015 at 12:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.