why firebase cloud messaging notification for web duplicate notifications - firebase

I'm making a web app with notification function. But the message I received was repeated.
The first one has no image. but second message has image and title is ${notificationTitle}123.
// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js');
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
// ...api key
}
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
image: payload.notification.image,
icon: payload.notification.image,
};
self.registration.showNotification(`${notificationTitle}123`, notificationOptions);
});

Related

how to avoid duplicate Push Notification

importScripts('https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.4.3/firebase-messaging.js')
firebase.initializeApp({...config});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log('sw-fb', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body:"something Body",
data:{...}
};
return self.registration.showNotification(notificationTitle, notificationOptions);
},
Here i am trying to show push notification from firebase, but for every single notification getting two notifications. 1st one is the default one and 2nd one is from my service worker.
can anyone help me to fix the duplicate default notification.
to avoid default notification ,when sending through fcm need to send notification data as below
var payload = {
notification:{},
data: {
title:'title',
body:'something body',
image:path,
icon...},
token: registrationToken
};
messaging.send(payload).then((result) => {console.log(result)})
and update srviceworker as
messaging.onBackgroundMessage((payload) => {
const { data }= payload;
const notificationTitle = data?.title;
const notificationOptions =
{ image:data.image, title:data.title, body: data.body, icon:data.icon }
self.registration.showNotification(notificationTitle, notificationOptions);
});

Firebase cloud function doesn't work on Cordova

I'm trying to send a notification to every user in my Cordova app, at a schedule date automatically. I tried to create a cloud function, but the log on firebase don't show any error.
I tried to make this function, and I'm using the cordova-plugin-firebase-lib to receive notifications, if I go to the firebase console and send it manually it works
//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref('/messages/{pushId}').onWrite( event => {
console.log('Push notification event triggered');
// Grab the current value of what was written to the Realtime Database.
var valueObject = event.data.val();
if(valueObject.photoUrl !== null) {
valueObject.photoUrl= "Sent you a photo!";
}
// Create a notification
const payload = {
notification: {
title:valueObject.name,
body: valueObject.text || valueObject.photoUrl,
sound: "default"
},
};
//Create an options object that contains the time to live for the notification and the priority
const options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToTopic("pushNotifications", payload, options);
});
when i try to add name and text to message on my data base nothing happens

Sending FCM notification using Cloud Functions .. Issue

I'm trying to send FCM notification through the Cloud functions but it's not working ...
Here is the code ... I doubt that the path to the db is not correct!
var functions = require("firebase-functions");
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/messages/{messageId}').onCreate(event => {
let payload = {
notification: {
title: 'Firebase Notification',
body: 'Coming from DB Trigger!',
sound: 'default',
badge: '1'
}
};
let tokens = 'e28NuXH_8gY:APA91bGdDjb....';
admin.messaging().sendToDevice(tokens, payload);
});
Here is the database design:
DB Image ONE
DB Image TWO

React native notifications in a Chat App

I'm working on a chat application and I currently have 6 different chat channels with a different firebase database for each of them. Every channels have firebase rules that define if an user can read and write in this channel. I want to send notifications to users when a new message is posted, but only the users that are part of the specified channel.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const _ = require('lodash');
admin.initializeApp(functions.config().firebase);
exports.sendNewMessageNotification = functions.database.ref('/GeneralMessage').onWrite(event => {
const getValuePromise = admin.database()
.ref('GeneralMessage')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
console.log(_.values(snapshot.val())[0]);
const { text } = _.values(snapshot.val())[0];
const payload = {
notification: {
title: 'New msg',
body: text,
}
};
return admin.messaging()
.sendToTopic('GeneralMessage', payload);
});
});
That's the code I currently have using firebase cloud function in /functions/index.js. When I send a message in the app, I have this output in firebase : Firebase cloud functions but the notifications isn't working in app.

Flutter: Firebase Pushnotification On Data Change

After getting the comment, i have deployed this folowing code to my firebase project and it was successfully deploed!.But there is no notifications been send to me.
Please check my Firebase Realtime database Screenshot here for better understanding.
[ITS SOLVED NOW:IT WILL SEND NOTIFICATIONS TO ONLY ONE ID ie My Admin Device]
WORKING CODE:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firbase);
exports.codeformypeople = functions.database.ref('items/{id}').onWrite(evt => {
const payload = {
notification: { title: 'New Customer Requested', body: 'Touch to Open The App', badge: '1', sound: 'default', }
};
const token ="Lsn-bHfBWC6igTfWQ1-h7GoFMxaDWayKIpWCrzC";//replace with ur token
if (token) {
console.log('Toke is availabel .');
return admin.messaging().sendToDevice(token, payload);
} else {
console.log('token error');
}
});
[
SEE THIS VIDEO LINK FOR MORE DETAILS
note:If your app is opened and minmized then it will show notification,but if the app is opened and you are using,or if the app is terminated force close then it will not work!!
You can use firebase cloud function to trigger notification. Here is snippet of cloud functions which i am using to trigger notification:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/Notifications/{pushId}')
.onWrite(( change,context) => {
console.log("Push Notification event triggered");
var request = change.after.val();
var payload = {
data:{
username: request.userName,
}
};
admin.messaging().sendToDevice(request.userTokenId, payload)
.then(function(response){
console.log("Successfully sent message: ",response);
console.log(response.results[0].error);
})
.catch(function(error){
console.log("Error sending message: ", error)
})
})
Below i have provided my notification structure, you can see below.This function will trigger if any new data is being pushed in database notification node. To see what is output/error you are getting when this function is trigger go to firebase admin panel > Functions > Logs.
You have deployed function code perfectly, but you forgot to add refresh tokenId in your database as you can see in above picture i am saving userTokenId in my database and in function admin.messaging().sendToDevice(request.userTokenId, payload) i am using that tokenId, this tokenId is used to send notification to particular device, you can get this tokenId using FirebaseInstanceId.getInstance().getToken() and save this in your fbproject1 > items database sturcture. please refer this & this

Resources