handling Group notification in react native firebase - firebase

i am trying to handle group notifications in my react native project using firebase cloud messaging. notifications come correctly in foreground/background and when app is killed but i have problem to group my notifications. i used groupChannel as the documentation said but when notifications have been sent to device , the newer one replaces the old one.
here is what i send through postman:
{
"to": "my-token",
"priority":"high",
"data": {
"title": "my title",
"body": "Lorem",
"remote": true,
"sound":"default",
"priority":"high",
"groupId":"Group2",
"tag":"GroupTag"
}
}
here are my codes:
this.notificationListener = firebase.messaging().onMessage(async message=>{
console.log(message,'foreground')
const {body,title,sound,groupId,tag} = message.data;
const GroupChannelId = new firebase.notifications.Android.ChannelGroup(
groupId,
'Group')
firebase.notifications().android.createChannelGroup(GroupChannelId);
const localNotification = new firebase.notifications.Notification()
.setTitle(title)
.setBody(body)
.setData(message.data)
.setNotificationId(groupId)
.android.setGroup(groupId)
.android.setBigText(body)
.android.setVibrate([600,300,200,300,500])
.android.setAutoCancel(true)
.android.setChannelId(groupId)
.android.setGroupAlertBehaviour(firebase.notifications.Android.GroupAlert.Children)
.android.setPriority(firebase.notifications.Android.Priority.High);
const date = new Date();
date.setMinutes(date.getMinutes() + 1);
firebase.notifications().scheduleNotification(localNotification,{
fireDate:date.getTime()
})
firebase.notifications().displayNotification(localNotification);
})

Related

Flutter: How do I send a push notification from the device itself?

I'm new to programming and I'm developing an app in which the user is suppose to get a notification 30 minutes before an event that's scheduled on the app. The schedule is saved in the firebase database and the device checks every 30 minutes to see if it's time to send an alert. If that condition becomes true, I want the device to send the notification so that the user will be alerted about the event. Every tutorial I saw only showed how to send notification through firebase itself. None of them covered how you can send them from the device.
I came across this code:
final postUrl = Uri.parse('https://fcm.googleapis.com/fcm/send');
final data = {
"registration_ids": tokens, //list of tokens
"collapse_key": "type_a",
"notification": {
"title": 'title',
"body": 'body',
},
"data": {
"data1": 'data 1', //data passed
}
};
final Map<String, String> headers = {
'content-type': 'application/json',
'Authorization': serverKey, //..................FCM server key
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
print('test ok push CFM');
return true;
} else {
print(' CFM error');
print(response.statusCode);
return false;
}
}
But isn't this bad practice since your server key is exposed? Are there any better and safe methods to do this using flutter??
I think checking the firebase database every 30 minutes from the device is not a good decision.
You can use/write a firebase cloud function. Using a firebase cloud function you can watch any document/field and try to write notification trigger logic like if a event is before 30 minutes then this cloud function will throw a notification via firebase messaging.
See https://firebase.flutter.dev/docs/functions/overview/ for more information.

PWA notification grouping

I have created a PWA and implemented push notifications.
From what I understand notifications can be replaced using tag and behaviour controlled using renotify. Google documentation here.
This may be a good way to keep down the amount of displayed notifications, but is there a way to group notifications in a PWA?
In native apps I have noticed that notifications get "grouped" or "stacked" into one notification if there are more than a certain amount of notifications. Can this be achieved in a PWA?
Code for showing a push notification:
self.addEventListener('push', function (event){
console.log('Push Notification received', event)
const defaultData = {title: 'New!', content: 'Something new happened!', openUrl: '/'}
const data = (event.data) ? JSON.parse(event.data.text()) : defaultData
var options = {
body: data.content,
icon: '/img/ico/manifest-512.png',
badge: '/img/ico/badge96.png',
// tag: 'myTag',
// renotify: true,
data: {
url: data.openUrl
}
}
event.waitUntil(
self.registration.showNotification(data.title, options)
)
})
Kind regards /K

Adding Conversion events to a cloud message using Firebase Admin SDK

I am able to send Push notifications using the code below but I am also required to associate "Conversion events" with the notification. This can be done through the console but I couldn't find how to do it with SDK.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "test1", "6165" },
{ "test2", "161" },
},
Notification =
{
Body = "",
Title = ""
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
Task<string> response = FirebaseMessaging.DefaultInstance.SendAsync(message, true);
// Response is a message ID string.
response.Wait();
Console.WriteLine("Successfully sent message: " + response);

How to receive FCM push notifications in service worker in Chrome Extension

I'm sending an FCM push notification from a Firebase backend to a Chrome Extension. I get it to show successfully in my Chrome Extension when it's in focus. I want it to show even if the Extension isn't in focus, but I can't get the service worker that's supposed to handle the notification even to fire.
I followed the Google tutorial to set up my JavaScript Chrome Extension client. I already tried this solution to not include a "notification" payload in my message, and this solution to register the worker manually (even though the tutorial doesn't say anything about either), but to no avail.
My service worker firebase-messaging-sw.js looks like this:
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
This is the POST request I use to send notifications (obviously with the correct SERVER_KEY and USER_TOKEN values):
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=<SERVER_KEY>
Cache-Control: no-cache
{
"data": {
"title": "Firebase",
"body": "Firebase is awesome",
"click_action": "http://localhost:5000/",
"icon": "http://localhost:5000/firebase-logo.png"
},
"to": "<USER_TOKEN>"
}
How do I get the service worker to receive the push notification and display it?
Thanks in advance :)
You can use Push API in service worker (firebase-messaging-sw.js):
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-messaging.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
this.onpush = event => {
console.dir(event.data.json());
// Here you can use event.data to compose Notification
// #see https://www.w3.org/TR/push-api/#pushmessagedata-interface
};

How to trigger an alert once receiving push notifications using Broadcast notifications?

Using MobileFirst Platform 6.3,
I am implementing the sendMessage API from WL.Server for pushing notification to all devices (Push.ALL).
The notification is successfully pushed into the device but it doesn't trigger an alert like NotifyAllDevice (as can be seen in the sample project for push notifications).
What can I do to trigger a dialog box with the message inside it, after the notification has arrived to my device?
function sendMessage(msg){
var notificationOptions = {};
notificationOptions.type = 0;
notificationOptions.message = {};
notificationOptions.message.alert = msg;
notificationOptions.target = {};
notificationOptions.target.platform = ['G','A'];
// set notification properties for GCM
notificationOptions.settings = {};
notificationOptions.settings.gcm = {};
notificationOptions.settings.gcm.sound = "default";
// set notification properties for APNS
notificationOptions.settings.apns = {};
notificationOptions.settings.apns.sound = "default";
//WL.Server.notifyAllDevices(userSubscription, notification);
WL.Server.sendMessage("PushNotifications", notificationOptions);
return {
result: "Notification sent to user :: "
};
}
For broadcast / tag based messages, the notifications are received on the client / app. in the callback
WL.Client.Push.onMessage(props, payload)
More info. on the API is found at -
http://www-01.ibm.com/support/knowledgecenter/SSZH4A_6.2.0/com.ibm.worklight.apiref.doc/html/refjavascript-client/html/WL.Client.Push.html%23onMessage
Here's how you would define the callback and display an in the app:
WL.Client.Push.onMessage = function(props, payload) {
alert("broadcastReceived invoked");
alert("props :: " + JSON.stringify(props));
alert("payload :: " + JSON.stringify(payload));
};

Resources