i am building mobile application using cordova and phonegap.
I want to display a popup on device screen when the notification reaches.Is there any plugin in cordova for this.
From https://programmingistheway.wordpress.com/2017/07/19/devextremephonegap-how-to-manage-push-notifications-with-fcm/
The 3 events registration, notification and error are managed only if the app is opened.
Registration: the APP registers itself to the push service, receiving
a unique registrationId. This event is useful if you want to store
this value to send notifications to single devices;
Notification: instead of show the classic notification pop up (depending on the
phone), the event notication shows a little pop up (using DevExtreme
feature) to read the message, if the APP is open (if the app is
closed, you will get the notification in the classic way);
Error: if the APP is open and the notification throws some error, here you can manage it.
So, the event you have to mangage is notification. This event is raised when a notification is delivered with the app in foreground (so, when the app is running).
Insert this code in the deviceReady event:
var push = PushNotification.init({
android: {
},
ios: {
alert: "true",
badge: "true",
sound: "true",
clearBadge: "true"
},
windows: {}
});
push.on('registration', function (data) {
// data.registrationId
DevExpress.ui.notify("Device registered " + data.registrationId, "success", 3000);
});
push.on('notification', function (data) {
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
// mostra la notifica se l'app è aperta
DevExpress.ui.notify(data.message, "info", 10000);
});
push.on('error', function (e) {
// e.message
// sarà da togliere, utilissimo in fase di debug
DevExpress.ui.notify(e.message, "error", 10000);
});
and insert the code you need in the notification event. In this case, DevExtreme is used, but if you don't use it you can just show an alert or look for what you need (example)enter link description here.
Related
How to skip/open a specific screen based notification. Example: When a user clicks on the notification, the application should open and go directly to the notifications page instead of the home page.
when i was using react-native-push-notification i mannage to get the text of my notification this way :
componentWillMount() {
var _this = this;
PushNotification.configure({
onRegister: function(token) {
_this.props.InitToken(token.token);
},
onNotification: function(notification) {
setTimeout(() => {
if(!notification['foreground']){
_this.props.InitNotif(notification['message']);
}
}, 1);
PushNotification.localNotificationSchedule({
title: 'Notification with my name',
message: notification['name'], // (required)
date: new Date(Date.now()) // in 60 secs
});
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "YourID",
});
}
where
_this.props.InitToken(token.token);
and
_this.props.InitNotif(notification['message']);
are redux based function that update your state with the notification token and message. When you'r state is updated whith the notification message your can change route ou display the message on screen.
PS:
i dont know if it was the good way but i was working
componentWillMount() is depreciated.
I have created firebase project for using Cloud Messaging . until now I have sent a message from backend to client successfully when the browser (chrome) is open but when I close the browser notification not sending until reopening of the browser in below code you can see my firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "My-Sender-Id"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
self.addEventListener('push', function(e) {
var data;
if (e.data) {
data = JSON.parse(e.data.text()).data;
} else {
data = {};
}
var title = data.title;
var options = {
body: data.body,
icon: 'assets/custom/img/logo.png',
vibrate: [100, 50, 100],
requireInteraction: true,
data: data.data ? data.data : null,
dir: "rtl",
actions: [{
action: data.action,
title: 'open',
icon: 'images/checkmark.png'
},
{
action: 'close',
title: 'close',
icon: 'images/xmark.png'
},
]
};
e.waitUntil(
self.registration.showNotification(title, options)
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
if (event.action != "" && event.action != "close") {
return clients.openWindow(event.action);
}
});
how can I have notification even browser is closed?
I believe you are using service worker for FCM, and the service worker only works when the browser is open ,as service worker is responsible for handling the push notification, when the browser is closed you won't receive any push notification, Actually the push notification will appear only when the browser is opened ,or the application for which you have configured FCM is open on chrome tabs but not focused, there is one work around or you say solution for it , that is make sure the chrome browser is active in the background even after closing chrome browser.
There is option in chrome settings
Goto Settings -> Advanced -> Continue running background apps when Google Chrome is closed make sure you enable it
i have tested the code of FCM , after enabling the option you will get the notification popup.
What you are trying to achieve should be accomplished using a database like firestore. When a notification is received at the time when browser is closed, in the service worker, you should add the code to save the notification message in the firestore so that when user opens the website again, you can retrieve the messages from the firestore and can display them to user. As soon as the browser is opened, any pending notification would be saved to the database by service worker.
I believe this should be the preferred way to achieve this.
I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.
Any ideas what I need to do to customize the message in the service worker?
Thank you very much!
For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71
short summary: do not include a "notification" element in your json message.
This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DB_URL',
projectId: 'YOUR_PROJ_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
tag: payload.data.tag,
data: payload.data.link,
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data));
});
JSON Message
{
"message": {
"token": "YOUR_TARGET_APP_TOKEN",
"data": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
"link": "https://yourapp.com/somewhere"
}
}
}
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.
The workaround I found for the web was to use the web browser native EH push to handle the event manually:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush
self.addEventListener('notificationclick', function(event) {
console.log('SW: Clicked notification', event)
let data = event.notification.data
event.notification.close()
self.clients.openWindow(event.notification.data.link)
})
self.addEventListener('push', event => {
let data = {}
if (event.data) {
data = event.data.json()
}
console.log('SW: Push received', data)
if (data.notification && data.notification.title) {
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: 'https://example.com/img/icons/icon-144x144.png',
data
})
} else {
console.log('SW: No notification payload, not showing notification')
}
})
When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.
Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).
If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.
I am using Ionic 2, and am trying to get Push Notifications working.
I have registered my app with Firebase, and can push notifications to it successfully.
I now need to set up, so that I can push notifications from my app. So I decided to use the following Cordova Plugin (cordova-plugin-fcm).
Question 1
When I follow it's instructions, by doing the following in my Ionic app:
app.ts
declare var FCMPlugin;
...
initializeApp() {
this.platform.ready().then(() => {
...
FCMPlugin.getToken(
function (token) {
....
I get the following Error at runtime:
EXCEPTION: Error: Uncaught (in promise): ReferenceError: FCMPlugin is
not defined
How do I solve this please?
Question 2
In order to send notifications from your app, the Cordova Plugin (cordova-plugin-fcm) instructs the following:
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
"notification":{
"title":"Notification title", //Any value
"body":"Notification body", //Any value
"sound":"default", //If you want notification sound
"click_action":"FCM_PLUGIN_ACTIVITY", //Must be present for Android
"icon":"fcm_push_icon" //White icon Android resource
},
"data":{
"param1":"value1", //Any data to be retrieved in the notification callback
"param2":"value2"
},
"to":"/topics/topicExample", //Topic or single device
"priority":"high", //If not set, notification won't be delivered on completely closed iOS app
"restricted_package_name":"" //Optional. Set for application filtering
}
This is not even Typescript or Javascript. So where does it go? I just don't understand. Any advise appreciated.
You should have FCMPlugin.js included in your HTML index file
find the path for js file into plugins directory of the app
Example : MyFCM\plugins\cordova-plugin-fcm\www\FCMPlugin.js
app.controller('AppCtrl', function(FCMPlugin,$scope,$cordovaToast,$cordovaDialogs,ionPlatform) {
// call to register automatically upon device ready
ionPlatform.ready.then(function (device) {
console.log('I am working');
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
$cordovaDialogs.alert(data.notification.body);
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
$cordovaDialogs.alert(data.notification.body);
//$cordovaToast.showShortCenter( JSON.stringify(data) );
}
},
function(msg){
$cordovaToast.showShortCenter('onNotification callback successfully registered: ' + msg);
},
function(err){
$cordovaToast.showShortCenter('Error registering onNotification callback: ' + err);
}
);
});
})
My application uses ACS Push Notification. I have implemented app badge in my application. But the problem is the appBadge doesn't incrementing automatically while receiving a push notification. I have used the following code in my app
var deviceToken;
Titanium.Network.registerForPushNotifications({
types: [
Titanium.Network.NOTIFICATION_TYPE_BADGE,
Titanium.Network.NOTIFICATION_TYPE_ALERT,
Titanium.Network.NOTIFICATION_TYPE_SOUND
],
success:function(e)
{
deviceToken = e.deviceToken;
SubscribeToPush(channelName, deviceToken, type);
},
error:function(e)
{
alert("Error: "+ ((e.error && e.message) || JSON.stringify(e.error)));
},
callback:function(e)
{
var badgeCount = Ti.UI.iPhone.getAppBadge();
badgeCount = badgeCount + 1;
Ti.UI.iPhone.setAppBadge(badgeCount);
}
});
I read here that "callback function" invoked upon receiving a new push notification. So I set the following code as callback to increment the badge.
callback:function(e)
{
var badgeCount = Ti.UI.iPhone.getAppBadge(); //Will return the app badges
badgeCount = badgeCount + 1; //Incrementing the appbadge
Ti.UI.iPhone.setAppBadge(badgeCount); //Setting new appbadge
}
It works while the app is open and when it receives a notification, callback get fired and when the app go to background, the badge get appeared. But I want to increment the badge number when the app is in background or exited. Can anyone help me to resolve this issue?
After lots of research I have created a sample application to increment the appBadge while receiving a server push notification. You can download the code from Increment the ios appBadge Titanium. Please follow the steps after downloading the resources folder.
Create a new mobile application project in Titanium.
Replace the resources folder with the one you downloaded.
Login to www.appcelerator.com, go to your app then go to Manage ACS
Create a new user as admin, set user as admin
Create a new Access Control List(ACS) using the admin user and give the ACL Name as 'SampleApp'
Upload the p12 certificate for push notification
Now Install the application to your iPhone and run the app...
Each user of the app should have a custom object which stores the number of notifications. I'm updating them while sending a push and clears it while I resume/open the application. I tested it with my iPhone devices and it works perfect. However it takes some delays since I have to call ACS multiple times.
UPDATE : Latest Titanium SDKs Support this feature by default.
What you need to do is to change the payload as follows:
var payload = {"alert":"Hi, This is a test notification", badge: "+1"};
/*+1 will increment the current appbadge by 1, number of appbadge will be saved in the ACS*/
Cloud.PushNotifications.notify({
channel: 'friend_request',
payload: payload
}, function (e) {
if (e.success) {
alert('Success');
} else {
alert('Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
And this will increase the appbadge by one. And you need to reset the appbadge when you resume/open of your application as follows
Cloud.PushNotifications.resetBadge({
device_token : myDeviceToken
}, function(e){
if(e.success){
Ti.UI.iPhone.setAppBadge(0);
} else {
//Error callback
}
})