Handling Push Notification action buttons with phonegap-plugin-push

Hello there,

I would like someone to provide a sample code for app side code for handling a push notification that involves action for android and ios as well as handling direction to a specific state.

I have read several pages from different places but they all seem to provide a piece and not the full picture.

Thanks!

For that purpose you should use ionics ngCordova wrapper:
http://ngcordova.com/docs/plugins/pushNotifications/

There are two really good examples how to handle push notifications in android and ios.

Do you want to redirect everytime you receive a push notification to a specific state or only in some cases?
If not you can pass additional data to a push notification.

I saw that and have part of this in my application. I want to be able to handle the callback being sent from the server. This is not shown in here.

Here is a screen shot of the type of notification i am getting in my app

I am want to be able to handle the ‘Email Guests’ and ‘Snooze’ in my app.

Here is the message that I am pushing from my server:
var message = new gcm.Message(); //create a new message

message.addData(‘title’, ‘Test Push with Action’);
message.addData(‘message’, ‘Follow me?’);
message.addData(‘sound’, ‘notification’);
message.addData(‘actions’, [{
“icon”: “emailGuests”,
“title”: “FOLLOW”,
“callback”: “follow”
}, {
“icon”: “snooze”,
“title”: “DISMISS”,
“callback”: “dismiss”
}, ]);
message.addData(“image”, “https://dl.dropboxusercontent.com/u/887989/antshot.png”);
message.addData(“style”, “inbox”);
message.addData(“summaryText”, “There are %n% notifications”);
message.addData(“content-available”, “1”);

And this is what I have at the app side but don’t know how to intercept the action pressed to behave accordingly :frowning:

Console logs on device when message is received:

Received Something !!!
Data …
image https://dl.dropboxusercontent.com/u/887989/antshot.png
sound notification
title Test Push with Action
message Follow me?
additionalData [object Object]
Additional data [object Object]
content-available 1
summaryText There are %n% notifications
actions [object Object],[object Object]
style inbox
collapse_key do_not_collapse
foreground false
cordova.js:310 Error in Success callbackId: PushNotification1990689049 : TypeError: Cannot read property ‘apply’ of undefined
cordova.js:312 Uncaught TypeError: Cannot read property ‘apply’ of undefined
cordova.js:310 Error in Success callbackId: PushNotification1990689049 : TypeError: Cannot read property ‘apply’ of undefined

App Side Code:

(how to get the action and handle???)

push.on(‘notification’, function(data) {
console.log(“Received Something !!!”)
console.log(“Data …”);
Object.keys(data).forEach(function (key) { console.log(key + " " + data[key]); })
// alert(data.title + " Message: " + data.message);
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData

  if (data.additionalData) {
    console.log("Additional data " + data.additionalData);
    Object.keys(data.additionalData).forEach(function (key) { console.log(key + " " + data.additionalData[key]); })
  } else {
    console.log('no additional data');
  }
});

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

Can anyone please help with this?

I have the same problem.
When I press in action button ‘emailGuests’ appear:

Error in Success callbackId: PushNotification1435666640 : TypeError: Cannot read property ‘emailGuest’ of undefined
cordova.js:314 Uncaught TypeError: Cannot read property ‘emailGuest’ of undefined

How to implement callback for action buttons with ponegap-plugin-push??
“actions”: [{
“icon”: “notify_icon_01”, // Need android/res/drawable icon_01.png file
"title": “Email”,
“callback”: “app.emailGuests”,
“foreground”: true
}]

Thanks.

Did anyone find the solution here?

I’m stuck using
app.callbackName giving me 'cannot read property callBackName of undefined’
or
window.callback giving me ‘cannot read property apply of undefined’

ok, found that one… you need to use window.callback. just make sure that you declare window.callback = function() {…} somewhere where you’re sure it’s already parsed in you app when the callback is fired. (ie. in your app boot sequence)

please see this

3 Likes

I faced the same problem. In all of the Cordova examples (without Ionic), the app variable is referenced. app is the convention for representing a Cordova application, and it’s available via the global window object.

I ended up creating an Angular factory, e.g., pushListener, and exposed it to the $window object:

// pushlistener.factory.js
(function (module) {
    module.factory('pushListener', function ($window) {
        var api = {
            callbacks: {}
        };

        $window.pushListener = api;

        return api;
    });
})(angular.module('starter.services'));

In my Ionic tab project, I then inject pushListener into run to ensure it’s initialized, but I call it on the $window object:

 module('starter', ['starter.services']).run( function ($ionicPlatform, $window, $cordovaDialogs, pushListener) {

	function initPush() {
 		$window.pushListener.callbacks.viewChats = function () {
		    $state.go('tab.chats');
		    push.finish(function (result) {
		        $cordovaDialogs('push:finish():result' + result);
		    }, function (rejection) {
		        $cordovaDialogs('push:finish():rejection' + rejection);
		    });
		};

		$window.pushListener.callbacks.snooze = function () {
		    $cordovaDialogs.alert('Do something later.');
		    push.finish(function (result) {
		        $cordovaDialogs('push:finish():result' + result);
		    }, function (rejection) {
		        $cordovaDialogs('push:finish():rejection' + rejection);
		    });
		};
	}
	
	$ionicPlatform.ready(initPush);
});

Finally, my (Android) push notification:

{
  "data": {
    "title": "You have unread chats!",
    "message": "Click here to read them.",
    "actions": [
        { "title": "VIEW CHATS", "callback": "pushListener.callbacks.viewChats", "foreground": true},
        { "title": "SNOOZE", "callback": "pushListener.callbacks.snooze", "foreground": true}
    ]
  },
  "registration_ids":["foobar"]
}

…and now all is well. :slight_smile: If anyone knows whether ionic exposes an object comparable to the Cordova app object, please let me know.

1 Like

Hi there, any update in this topic? I am in the same situation. I used your code but the functions are not being executed as callback… Did you find how to do it with ionic? Thanks in advance

for those who cannot avoid using app.* is callback name, you can simply define a global object named app, e.g.:

app = {greet: function(data){console.log('greeting from push notification')}}

while your push notification comes with callback=app.greet

Does anyone know how to do this in Ionic 2?

Has anyone found a solution for Ionic 2?

I sent a pull request to the phonegap-plugin-push to be able to use events instead of callbacks. The PR wasn’t merged yet, so for now you can use my branch (https://github.com/akz92/phonegap-plugin-push). I updated the docs too to explain how to use events.

Great jobs! Can you please also guide how, where and which event should I subscribe in my Ionic 2 app?
For example I have an action Reply with callback specified as onReply. As per my understanding it will emit event onReply when user click’s Reply button, but where and how do I subscribe for this event in my ionic 2 app?

Would it be similar to the way we subscribe for events (notification, registration, error etc.) of push something like?

push.on(‘onReply’, (e) => {
console.log(e);
});

Exactly Naveed! It emits the callback name as an event on the push instance, like ‘registration’ and ‘notification’

That’s awesome! makes it really simple and straight forward :slight_smile:

I just started with ionic 2 and i hope my sharing will help. You can use the callback function under window context. eg for ionic 2 like below

(<any>window).pushcb = function (){ 
  alert('Notification Button Callback');
};

You can for example add an event emitter inside the callback function to trigger further actions.

1 Like

Ok… we can simply add “onReply” in notification json like this…
“actions”: [
{ “icon”: “emailGuests”, “title”: “EMAIL GUESTS”, “callback”: “onReply”, “foreground”: true},
{ “icon”: “snooze”, “title”: “SNOOZE”, “callback”: “onReply”, “foreground”: true}
]

Is it correct ? Please help me…

Is it working in ionic 2 ? I used this way. But callback not getting called.

@toscpsx Yes… It works for me. Thanks. But I need to get the notification data through this callback. How to do ?