I have an Ionic 4 app which I have integrated with Firebase for authentication etc. I want to implement Firebase's cloud messaging so I can push messages to my app on both Android and iOS. I have done this pretty easily on iOS and I have sent a message via Postman which shows on my iPhone and I see the JSON of the message I have sent. When I try it on Android it doesn't work. Both devices receive the message but handle it very diferently.
I have read in a lot of places that you need to set the click_action to FCM_PLUGIN_ACTIVITY but when I do that the app doesn't even open on Android. When I take it out the app loads when you click the message but it doesn't show the body of the message like on iOS in my alert.
import { FCM } from '#ionic-native/fcm/ngx';
...
constructor(public platform: Platform, public fcm: FCM)
...
this.platform.ready().then(() => {
this.fcm.onNotification().subscribe(data => {
alert(JSON.stringify(data));
});
this.fcm.onTokenRefresh().subscribe(token => {
// Register your new token in your back-end if you want
// backend.registerToken(token);
});
}).catch((error) => {
this.showFailureMessage(error.message);
});
This is what I am posting off to... https://fcm.googleapis.com/fcm/send
{
"notification":{
"title":"My Title",
"body":"My Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY"
"icon":"fcm_push_icon",
},
"data":{
"type":"Something",
},
"to":"/topics/all",
"priority":"high",
"restricted_package_name":""
}
Any help would be very much appreciated.
You seem to be missing the data.wasTapped part in your subscribe. Here, try this:
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
alert('Received in background');
alert(JSON.stringify(data));
} else {
alert('Received in foreground');
alert(JSON.stringify(data));
}
});
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'm working on a NativeScript mobile application where I'm using nativescript-plugin-firebase to retrieve a Firebase token I then send to Adobe Mobile Services so that I can send push notifications from there to users of both platforms (Android and iOS):
FirebasePlugin.init({
onMessageReceivedCallback: () => { ... },
onPushTokenReceivedCallback: (token: string) => {
AdobeAnalytics.getInstance().optIn();
AdobeAnalytics.getInstance().setPushIdentifier(isAndroid ? token : new NSData({ base64Encoding: token }));
}
});
This works fine on Android, where I can then send notifications from AMS to individual devices using the token or to multiple ones using AMS's segments.
However, on iOS it only works using the token, as AMS thinks there are no iOS devices registered. The requests triggered by setPushIdentifier returns 200 OK and something like this on both platforms:
{
"d_blob": "...",
"d_mid": "...",
"d_ottl": 7200,
"dcs_region": 6,
"ibs": [],
"id_sync_ttl": 604800,
"subdomain": "mysandbox",
"tid": "..."
}
I use a modified version of nativescript-adobe-marketing-cloud 1.5.0 that exposes that setPushIdentifier, but the implementation doesn't change.
I have also tried replacing nativescript-plugin-firebase with push-plugin, in which case I get an APNs token when using iOS instead of a Firebase one:
PushPlugin.init({
onMessageReceivedCallback: () => { ... },
onPushTokenReceivedCallback: (token: string) => {
AdobeAnalytics.getInstance().optIn();
AdobeAnalytics.getInstance().setPushIdentifier(isAndroid ? token : new NSData({ base64Encoding: token }));
}
});
But the same thing happens.
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);
}
);
});
})
I have a problem with push notifications unregister. I am able to register the device and get the token, also sending notifications too, but I would like to add the unregister feature too. Here is the code y wrote for it:
var unsubscribeNotification = function unsubscribeNotification() {
try {
pushNotification.unregister(
function(e) {
//unRegister Success!!!
alert('unRegister Success');
},
function(e) {
//unRegister Failed!!!
alert('unRegister Failed');
});
}
catch(err) {
//Handle errors here
alert(err.message);
}
}
I also put a button to run the unsubscribeNotification() function when you click it. After a few seconds the application stops, no error, no messages, nothing!
I am using a Galaxy S3, I think it has Android 4.1
Thanks for the help!