Firebase Cloud Messaging not working with Samsung Internet - firebase

I'm setting up Firebase Cloud Messaging to do push notifications on the web. It works but only with Chrome (Windows and Android) and Firefox(Android) so far. It's not working on Samsung Internet Browser (the browser that comes pre-installed on Samsung's phones) and I haven't gotten a chance to test on iOS so far.
I've tried adding the sender id as gcm_sender_id to the Cloud Function I'm using as well as to the manifest.json file to no avail. Below is how the notification body is set up.
// Create notification content
const notification = admin.messaging().Notification = {
title : 'My test Title',
body : `Lorem Ipsum Dolor`,
};
const payload = admin.messaging().Message = {
notification,
webpush:{
notification : {
vibrate: [200, 100, 200],
icon: 'https://www.goodhousekeeping.com/life/pets/g4531/cutest-dog-breeds/', //A random dog photo
fcm_options: {
link: 'https://www.youtube.com',
gcm_sender_id : '<SENDER_ID>',
},
},
},
topic: '<TOPIC>'
};
//Send notification
return admin.messaging().send(payload);
Is there anything I can do to get this to work on Samsung Internet? Service Workers have been supported since v4 and the device has v9. It should be noted that even on the devices that receive it, when I click on it, it doesn't open up the website I set in fcm_options nor does it follow the vibrate pattern but it does load the icon.
UPDATE: As of April 2020 FCM is completely incompatible with iOS Chrome and Safari

So I know this probably isn't helpful but it 'magically' started working today. The browser version is Samsung Internet v10.
firebase-messaging-sw.js
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/7.13.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.13.2/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
measurementId: ''
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(payload => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification
const notificationTitle = payload.data.title;
const notificationOptions = {
body: payload.data.body,
priority: payload.data.priority,
vibrate: payload.data.vibrate,
icon: payload.data.icon,
click_action: payload.data.link,
link: payload.data.link
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
//Open browser window or focus it if it is open on notification click
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(self.clients.openWindow('www.yourwebsitehere.com'));
});
Cloud function to send notifications
//Sends notifications to users when the statistics document is updated
exports.sendNotifications = functions.firestore.document('restaurant/statistics').onUpdate(async (snapshot,context) =>{
//Get updated document data
const updatedData = snapshot.after.data();
const payload = admin.messaging().Message = {
data: {
title: updatedData.title,
body : updatedData.body,
icon: updatedData.icon,
link: updatedData.link,
vibrate: "[300, 200, 300]",
priority: "high"
},
topic: 'statistics'
}
return admin.messaging().send(payload);
});

Related

why firebase cloud messaging notification for web duplicate notifications

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);
});

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

firebase set background message handler

I have been trying to customise notification message in front end, i.e if a field is not set send in notification, I am trying to add it.
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
var config = {
apiKey: "x",
authDomain: "y",
databaseURL: "z",
projectId: "a",
storageBucket: "b",
messagingSenderId: "1"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
console.log('came here');
console.log(messaging.bgMessageHandler);
console.log(messaging.setBackgroundMessageHandler,'dsafdsadasfd')
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'
};
console.log(notificationOptions)
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
console.log(messaging.bgMessageHandler);
while executing the above code, I am not getting an console of [firebase-messaging-sw.js] Received background message ', payload, even though i am getting notification.
Why is the setBackgroundMessageHandler not working?
It looks like problem within the json request that you made to send the message while app is running in background.
Note: If you set notification fields in your HTTP or XMPP send request, those values take precedence over any values specified in the service worker.
https://firebase.google.com/docs/cloud-messaging/js/topic-messaging
So,Following format won't call the background handler :
{
to: "e-DLMv........._DiL",
notification: {
body: "Backgound-Message"
}
}
Send message with notification inside data (It will work) :
{
to: "e-DLMv........._DiL",
data: {
notification: {
body: "Backgound-Message"
}
}
}

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

Fire-base web notification not received while no errors

I am working with web app in which I want to integrate Firebase Notifications but after I setup all the requirements I tried to use Firebase notification composer to test it, I got no errors and the status of the message was completed but I received nothing neither on background nor in foreground.
here is my code
index.html
<script src="https://www.gstatic.com/firebasejs/4.10.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "MY_API_KEY",
authDomain: "app.firebaseapp.com",
databaseURL: "https://app.firebaseio.com",
projectId: "app",
storageBucket: "app.appspot.com",
messagingSenderId: "MY_SENDER_ID"
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.usePublicVapidKey("BLWwgk4yFuoNHdPDccuDnXYmhxZA8kwpWArWaE3t7njDT90-30dcWlJIhFbXxMpfXczcvtU8AvMf_F1EJg8Qy");
messaging.requestPermission().then(function(res) {
console.log('test')
messaging.getToken().then(function(res){
console.log(res)
})
})
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('Token refreshed.');
})
.catch(function(err) {
console.log('Unable to retrieve refreshed token ', err);
});
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
</script>
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');
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
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
status of Firebase notification composer
Notes:
no errors on browser console.
no errors on Firebase console.
i had the same problem then i figured out that the version of firebase im using in the foreground is different than the version in sw, so i changed to the same version i use in the foreground and the problem is solved. Hope this help
I had the exact same problem. The problem was not in my front-end code at all but in the requests sent from firebase console. I would suggest you use Postman or your own backend to send a request to see if it works.
Heres a quick demo of my postman request -
method: POST
url : https://fcm.googleapis.com/fcm/send
Headers :
"Content-Type": "application/json",
"Authorization": (Your server key which is found in Cloud messaging settings in firebase console) Edit: Make sure to add "key=" before your server key. Example - "Authorization" : "key=AAAA7_.......QRIM"
Body:
"to" : (Your front end app token),
"data" : {
"body" : "Test message",
"title" : "Test title"
}
Hope this helps

Resources