FCM Web send message succeeds but nothing appears in Browser - javascript

I am sending following Notification
Authorization:key=A.....
Content-Type:application/json
{
"to" : "cBx_ErhkhNw:APA91bEzwHvZ2daEK15Y3A0VAprxPV-4GGq10FjlrFnHzCs8xSJXz2lATjh9AoLRQvnSseT6r4ggApC6TbtD9M_sI_BDDmycZ1TEVn0HaF5pAABeSbHqcOK-kmkPqOve1VThUaUIXQy4",
"notification": {
"title": "Test Nachricht",
"body": "This is a message from FCM to web"
},
"priority": "high",
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
And have following code:
app.js
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "<AUTH_DOMAIN>",
databaseURL: "<DB_URL>",
projectId: "atlas-test-35d33",
storageBucket: "<STORAGE_BUCKET>",
messagingSenderId: "817272374311"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("<PUBLIC_KEY>");
messaging.requestPermission()
.then(function() {
console.log("Permission granted");
return messaging.getToken()
})
.then(function(token) {
console.log(token)
})
.catch(function(err) {
console.log(err)
})
console.log("listenting")
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
// ...
});
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/5.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.9.0/firebase-messaging.js');
var config = {
apiKey: "<KEY>",
authDomain: "<AUTH_DOMAIN>",
databaseURL: "https://atlas-test-35d33.firebaseio.com",
projectId: "atlas-test-35d33",
storageBucket: "<STORAGE_BUCKET>",
messagingSenderId: "817272374311"
};
firebase.initializeApp(config);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
When I try to send a Notification to the fcm Server I get following response:
{
"multicast_id": 5394725759940263108,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1552646324437940%e609af1cf9fd7ecd"
}
]
}
Which seems, like everything is fine for me. But I dont receive anything in my Web application. I just hardcoded the "to" token for testing purposes but I dont think thats the Problem.
Do you have any clue whats the problem, or is there any debug possibility.
Thanks!

Related

Js/Firebase - Unable to receive notification

Here is my code:
<script src="/js/firebase.js" type="module"></script>
firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js";
import { getMessaging, getToken} from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js";
import { onBackgroundMessage } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging-sw.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const bbFirebase = initializeApp(firebaseConfig);
const messaging = getMessaging();
// Add the public key generated from the console here.
getToken(messaging, { vapidKey: 'MY_KEY_HERE' }).then((currentToken) => {
if (currentToken) {
console.log("TOKEN: " + currentToken);
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve a registration token for use with FCM.
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
} else {
console.log('Unable to get permission to notify.');
}
});
}
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.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.16.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging-compat.js');
/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
*/
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "G-JK625X6GX2"
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
console.log(payload.notification.title);
});
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ');
console.log(payload.notification.title);
});
When I execude the code I see the output of console.log("TOKEN: " + currentToken);
So token is generated. When I try to send notification to this token I am monitoring the browser console but no notification seems to be received. Any idea why ?
P.S.
I am trying this locally on my Mac using Valet as service for the domain.

Browser push notifications only on logged in | Firebase

I was implementing Firebase Browser push notifications in a React Project,
But I want the browser push notifications to come only when the user is logged in to the my website or application.
My requirement is:
Send Browser notifications to the user who are signed in, with their name, and some other details.
For the users not signed in, a generic message should go to them.
My service-worker file and the push-notifications file is as follows:
push-notifications.js
import firebase from 'firebase';
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
});
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log("Loading...",payload);
alert("Firebase is awesome");
});
}
export const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('token: ', token);
return token;
} catch (error) {
console.error(error);
}
}
export const getMessagingToken = async () => {
try {
const messaging = firebase.messaging();
const token = await messaging.getToken({vapidKey:
"xxx"});
return token;
} catch (error) {
console.error(error);
}
}
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
});
const messaging = firebase.messaging();
console.log(messaging);
Everything is working fine, but I want to send the notifications only to the users that have currently logged in to the website.
And some notifications to the users that are not logged in to the application.
I am not able to find any resource on firebase offical site for the same.
It would be great help if you share any relevant resources or answer the way to complete the requirement.
Thanks in advance!
Feel free to ask in case of any queries.

Firebase web push notification sent successfully but not received by the client

I'm using firebase web push notifications API and sending post request with the message I want to display on the client-side with Postman and/or from the firebase notifications composer, the message is being sent successfully but it is not being received, how can I fix this?
This is the response I get
{
"multicast_id": 6360733777037549929,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1592759038463623%cc9b4facf9fd7ecd"
}
]
}
I'm using Firebase hosting, and including the entire Firebase Javascript SDK, although I already tried including only firebase-messaging SDK.
<body>
<h1>Some Firebase app</h1>
<script src="/__/firebase/7.15.3/firebase.js"></script>
<script src="/__/firebase/init.js"></script>
<script type="text/javascript">
const messaging = firebase.messaging();
messaging.requestPermission()
.then(()=>{
console.log('Permission Granted');
return messaging.getToken()
})
.then((token)=>{
console.log(token);
})
.catch((err)=>{
console.log(err);
})
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
</script>
</body>
With the token I get, and with my server key I send the following request
Method: POST
URL: https://fcm.googleapis.com/fcm/send
Headers: {
Authorization: "key=myServerKey",
Content-Type: "application/json"
}
Body: {
"to" : "token",
"notification" : {
"body" : "Test message",
"title" : "Test title"
}
}
And this is how I handle the message on firebase-messaging-sw.js file
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
Which you want to receive message in the Foreground(has focus), or in the Background (service worker)?
in the Background (service worker)
Could you try the following code?
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
if (firebase.messaging.isSupported()) {
firebase.messaging();
}
See https://firebase.google.com/docs/cloud-messaging/js/receive
If you set notification fields in your message payload, your setBackgroundMessageHandler callback is not called, and instead the SDK displays a notification based on your payload.
Or, Could you try samples?
See:
https://github.com/firebase/functions-samples/tree/master/fcm-notifications
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/public/main.js
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/public/firebase-messaging-sw.js

FCM Cannot receive messages on WebApp

Well, simply put, I cannot receive messages via my WebApp using JS. I am receiving tokens and I am able to send messages via Firebase console to the WebApp's token, but I am not getting any receiving.
Here is my JS Code:
var config = {
apiKey: "AIzaSyBLCsBQVXLsDjPhjdkvJVMGyDUcfWrFtQU",
authDomain: "php-test-project-78c66.firebaseapp.com",
databaseURL: "https://php-test-project-78c66.firebaseio.com",
projectId: "php-test-project-78c66",
storageBucket: "php-test-project-78c66.appspot.com",
messagingSenderId: "856365479454"
};
firebase.initializeApp(config);
$(document).ready(function(){
const messaging = firebase.messaging();
messaging.requestPermission().then(function() {
console.log("Permitted");
return messaging.getToken();
}).then(function(token) {
console.log(token);
}).catch(function(error) {
console.log("Not Permitted");
});
messaging.onMessage(function(payload) {
console.log("TEST");
console.log("Message received. ", payload);
});
});
Upon sending message via Firebase Console, I do not receive anything. I send by using TokenID.
PS: The keys are of a Dev Testing App, hence I kept it in. If admins consider this a problem then you may remove it.

Can't receive notification with Firebase Cloud Messaging

I'm having an issue with Firebase Cloud Messaging (I'm trying to use it in the web) in which I get the Token and when i use it to send a notification , it give me a good response like this:
{"multicast_id":5064947793483036169,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1496136155591444%e609af1cf9fd7ecd"}]}
but i don't receive the notification.
This is the script that should receive the notification:
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase-app.js">
</script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase-messaging.js"></script>
<script>
var config = {
apiKey: "AIzaS.........7AP0",
authDomain: "prova-notifications.firebaseapp.com",
databaseURL: "https://prova-notifications.firebaseio.com",
projectId: "prova-notifications",
storageBucket: "prova-notifications.appspot.com",
messagingSenderId: "59.......20"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
return messaging.getToken();
})
.then(function(token) {
console.log(token);
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
});
what am I doing wrong?
EDIT: Here a sample payload that i'm sending:
Host: fcm.googleapis.com
Authorization: key=AAAAilrlPU.........LBA90EJk
Content-Type: application/json
{
"notification": {
"title": "Portugal vs. Denmark",
"body": "5 to 1"
},
"to": "eHdpi3OX..........5AvG"
}

Categories

Resources