Can't receive notification with Firebase Cloud Messaging - javascript

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"
}

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.

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 Web send message succeeds but nothing appears in Browser

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!

Firebase error on web token notification

I am trying to send the notification to the specific user using firebase. Going on with tutorials, I could not solve this in the beginning phase.
Here is my js:
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("");
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
return messaging.getToken();
}).then(function(token){
console.log(token);
})
function getRegToken(){
messaging.getToken().then(function(currentToken) {
if (currentToken) {
// sendTokenToServer(currentToken);
console.log(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}
I have inserted correct parameters inside the config and public key

The site has been updated in the background Chrome - Firebase

When I push a notification on chrome the messaging.onMessage()does't work(when I'm on page) and I don't see any notification(when I'm off the page). The only thing that is displayed is a pop up which says The site has been updated in the background but I don't have that issue in firefox. I've looked around about this issue and found out it is a semi-common one, but I couldn't modify my code in order to get it to work properly.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Notifications</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
/**
* Created by nikos on 13/7/2017.
*/
console.log('APP.JS');
var config = {
apiKey: "AIz..",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "locpushweb",
storageBucket: "locpushweb.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log("Have Permission");
return messaging.getToken();
}).then(function (token) {
console.log(token);
}).catch(function (err) {
console.log("Error: " + err)
});
messaging.onMessage(function (payload) {
console.log(payload);
})
firebase-messaging-sw.js
/**
* Created by nikos on 13/7/2017.
*/
console.log('SW');
importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase-messaging.js');
var config = {
apiKey: "AIz..",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "locpushweb",
storageBucket: "locpushweb.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
// messaging.setBackgroundMessageHandler(function (payload) {
// var data = JSON.parse(payload);
// self.registration.showNotification(data.title, {
// body: data.body,
// icon: data.icon,
// click_action: data.click_action,
// time_to_live: data.time_to_live,
// data: data.data,
// tag: data.tag
// });
// });
Lastly, this is the curl command:
curl -X POST -H "Authorization: key=AAAAZGd...." -H "Content-Type: application/json" -d '{
"notification": {
"title": "Portugal vs. Denmark",
"body": "5 to 1",
"icon": "firebase-logo.png",
"click_action": "http://localhost:8081"
},
"to": "cxfoMyjwsOY:APA91bFnOQlYxw3iPlbcc714wI5BFWLfEXvmT1FRTL0SJNuy1AOTfah4EKTdvoi1SvnX8SpD9CUD1D-I8GdKcIb-M1l65NFc8xhJNF2iBffERN9yWSNnN2_CHqodcpMMSyC_IDKZJ0GH"
}' "https://fcm.googleapis.com/fcm/send"

Categories

Resources