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
Related
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.
Hi I have Web based fcm setup using django and plain html
I Have refer this https://firebase.google.com/docs/cloud-messaging/js/receive#handle_messages_when_your_web_app_is_in_the_foreground
HTML
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const messaging = getMessaging();
// THIS IS NOT WORKING
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
console.log('Message received. ', payload);
console.log('Message received. ', payload);
});
getToken(messaging, { vapidKey: '' }).then((currentToken) => {
if (currentToken) {
console.log('11111111')
console.log(currentToken)
console.log(currentToken)
} else {
console.log('222222222')
// 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);
// ...
});
I am using Vue js on client-side and node js on the backend side. I am sending data message and it is getting received by the client-side when the browser's tab is inactive. But when the tab is active, it doesn't receive notification.
Here is my code on client-side
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<apiKey>",
authDomain: "<authDomain>",
databaseURL: "<db>",
projectId: "<projectId>",
storageBucket: "<storageBucket>",
messagingSenderId: "<senderId>",
appId: "<appId>"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.usePublicVapidKey(
"<KEY>"
);
messaging
.requestPermission()
.then(function() {
retrieveToken();
console.log("Notification permission granted.");
})
.catch(function(err) {
console.log("Unable to get permission to notify. ", err);
});
function retrieveToken() {
messaging
.getToken()
.then(deviceToken => {
if (deviceToken) {
console.log(deviceToken);
messaging.onMessage(payload => {
console.log("Message received. ", payload);
});
} else {
console.log(
"No Instance ID token available. Request permission to generate one."
);
}
})
.catch(err => {
console.log("An error occurred while retrieving token. ", err);
});
}
}
</script>
And here is my server side code
var message = {
data: {
score: "850",
time: "2:45"
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin
.messaging()
.send(message)
.then(response => {
// Response is a message ID string.
console.log("Successfully sent message:", response);
})
.catch(error => {
console.log("Error sending message:", error);
});
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!
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"
}