I have problems with firebase push notifications. The onMessage event is not triggered
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js');
firebase.initializeApp({
apiKey: "some_data",
authDomain: "some_data",
databaseURL: "some_data",
projectId: "some_data",
storageBucket: "some_data",
messagingSenderId: "some_data",
appId: "some_data",
measurementId: "some_data"
});
var messaging = firebase.messaging();
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
});
index.html
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js"></script>
<script>
firebase.initializeApp({
apiKey: "some_data",
authDomain: "some_data",
databaseURL: "some_data",
projectId: "some_data",
storageBucket: "some_data",
messagingSenderId: "some_data",
appId: "some_data",
measurementId: "some_data"
});
if ('Notification' in window) {
navigator.serviceWorker.register("js/firebase-messaging-sw.js")
.then((registration) => {
var messaging = firebase.messaging();
messaging.useServiceWorker(registration);
console.log(messaging);
if (Notification.permission === 'granted') {
subscribe(messaging);
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
});
}
$('#subscribe').on('click', function () {
subscribe(messaging);
});
});
}
function subscribe(messaging) {
messaging.requestPermission()
.then(function () {
messaging.getToken()
.then(function (currentToken) {
console.log(currentToken);
if (currentToken) {
sendTokenToServer(currentToken);
}
})
.catch(function (err) {
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.warn('not granted', err);
});
}
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer(currentToken)) {
console.log('Отправка токена на сервер...');
var url = '';
$.post(url, {
token: currentToken
});
setTokenSentToServer(currentToken);
}
}
function isTokenSentToServer(currentToken) {
return window.localStorage.getItem('sentFirebaseMessagingToken') == currentToken;
}
function setTokenSentToServer(currentToken) {
window.localStorage.setItem(
'sentFirebaseMessagingToken',
currentToken ? currentToken : ''
);
}
</script>
I'm able to get token and send it to the server. But when I send request from postman
https://fcm.googleapis.com/fcm/send
{
"notification": {
"title": "test",
"body": "test",
"click_action": "http://localhost:8001/"
},
"to": "token"
}
I can see nothing on web page, no messages in (response in postman has 200 status)
What is the right way to get notifications from firebase? Or what am I doing wrong?
First of all, my postman request was not absolutely right. There are two types of firebase requests, one is for only active browser tabs and second can work in the background. I used the first, that's why I can't see onMessage didn't trigger.
The postman request should be
https://fcm.googleapis.com/fcm/send
{
"data": {
"title": "test",
"body": "test",
"click_action": "http://localhost:8001/"
},
"to": "token"
}
Secondary, before subscribing and sending token to the server, messaging.usePublicVapidKey() must be called
And the last one, messaging.onMessage also must be before sending token to the server
Related
I am trying to fetch my device token in javascript. I have included these imports in my HTML page:
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-database-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging-compat.js"></script>
My javascript:
const firebaseConfig = {
messagingSenderId: "MY SENDER ID FROM CONSOLE",
apiKey: "MY API KEY FROM CONSOLE",
authDomain: "domain_name.firebaseapp.com",
projectId: "domain_name",
storageBucket: "domain_name.appspot.com",
messagingSenderId: "01234643924812",
databaseURL: "https://domain_name-default-rtdb.firebaseio.com",
appId: "1:1230535236326:web:f0fc4f32t23t235122e112c800"
};
const app = firebase.initializeApp(firebaseConfig);
(async()=>{
try {
await firebase.messaging().requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
})();
When I execute the code, I get this error:
TypeError: firebase.messaging(...).requestPermission is not a function
What am I doing wrong?
I am trying to integrate firebase cloud messaging 'FCM' on my payment page. it shows numberTokensSuccess 1 but no payload. I am writing the output to console.I am not getting any error.It is not working. Please help
I'm using https://github.com/brozot/Laravel-FCM .
I have added to top of the page
<script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-messaging.js"></script>
<link rel="manifest" href="{{ asset('core/manifest.json') }}" />
my firebase.js <script src="{{ asset('assets/js/firebase.js') }}"></script>
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
measurementId: "XXX"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log("Notification permission granted");
return messaging.getToken();
}).then(function(token) {
$('#device_token').val(token);
console.log(token);
}).catch(function (err){
console.log("Unable to get the permission to notify",err);
});
messaging.onMessage((payload) => {
console.log(payload);
});
firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.21.1/firebase-messaging.js");
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
measurementId: "XXX"
};
firebase.initializeApp(firebaseConfig);
const msg = firebase.messaging()
msg.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message',payload);
var notificationTitle = 'Background Message Title';
var notificationOptions =
{
body: 'Background Message Body',
icon: '/firebase-logo.png'
}
return self.registration.showNotification(notificationTitle, notificationOptions);
});
i have a problem with foreground push notifications.
I just want to get the data in the console for the moment but it didn't work. I follow the guide on firebase documentation but this function is never triggered...
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
Background notifications works as expected.
Here is my VueJs file
import * as firebase from "firebase/app";
import 'firebase/messaging';
const config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("");
export default {
name: 'App',
mounted() {
messaging.onMessage((payload) => { // Don't work here
console.log('Message received. ', payload);
});
this.getMsgPushToken();
},
methods: {
...mapMutations('auth', ['mutMsgPushToken']),
getMsgPushToken() {
let that = this
messaging.requestPermission().then(async function() {
messaging.getToken().then((token) => {
that.mutMsgPushToken(token); // Where i get the FCM token
})
}).catch((err) => {
console.log('Unable to get permission to notify.', err);
});
},
},
};
And my service worker
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': ''
});
const messaging = firebase.messaging();
If you have any idea of what i'm missing, i would love to hear it ha ha
**Edit: This is definitely a Github Pages issue. I deployed to Firebase Hosting and everything works as it should.
Here's my js to get the token. It is fully functional when running from localhost.
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log('have permission');
return messaging.getToken();
console.log(messaging.getToken());
})
.then(function (token) {
newToken = token
console.log(newToken);
})
.catch(function (err) {
console.log(err);
})
messaging.onMessage(function (payload) {
console.log('onMessage: ', payload)
})
Here's is what is in my firebase-messaging-sw.js file:
importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js")
importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-messaging.js")
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
// const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const title = 'hello world';
const options = {
body: payload.data.status
}
return self.registration.showNotification(title, options)
})
I get the following error when I try to use it from Github Pages:
Failed to register/update a ServiceWorker for scope
‘https://adambeck7.github.io/firebase-cloud-messaging-push-scope’:
Load failed with status 404 for script
‘https://adambeck7.github.io/firebase-messaging-sw.js’
I am trying to send data form my server to FCM, so that it can be shown on a specific section of my web page. It's like a stock application for example, where the data is constantly updated. In the same way am trying to achieve. So far I have configured it to receive data from FCM and it is being received. But the problem is that it shows the notification to like. My colleague are working on the same there is a option to send only data to the android app and hide notifications to be shown. Likewise I want to do it hear on web, but am unable to do it.
(function () {
// Initialize Firebase
var config = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "test-xxxxxxxx.xxxxxxxx.com",
databaseURL: "https://xxxxxx-xxxxxxxx.firebaseio.com",
projectId: "xxx-469e9",
storageBucket: "",
messagingSenderId: "xxxxxx"
};
firebase.initializeApp(config);
// Retrieve Firebase Messaging object.
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);
// ...
});
}());
on firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: "xxxxxx",
authDomain: "xxxx-xxxxxxxxxx.com",
databaseURL: "https://xxx-xxx.firebaseio.com",
projectId: "xxxx-xxxxxxxxxx",
storageBucket: "",
messagingSenderId: "xxxxxxxxxxxx"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
A hack would be to close the notification just after...
messaging.setBackgroundMessageHandler(function (payload) {
var realPush = true;
if(realPush)
{
const notificationOptions = {
body: "It is a REAL push",
data:"true"
};
//We display the notification
return self.registration.showNotification(title, notificationOptions);
}else
{
const notificationOptions = {
body: "It is a SILENT push",
data:"false"
};
//We display a fake notification
return self.registration.showNotification('To delete',notificationOptions).then(function () {
self.registration.getNotifications().then(notifications => {
console.log(notifications);
for (var i =0;i<notifications.length;i++)
{
if(notifications[i].data != "true")
{
//then we destroy the fake notification immedialtely !
notifications[i].close();
}
}
})
});
}
});
The realPush parameter is of course managed by yourself