firebase push notification onMessage payload not working in php - javascript

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

Related

Unable to request permission to fetch device token in javascript

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?

How to get value from firebse remote config in my web?

I created a firebase project and created a remote config to place setting values, but I cannot read it in my web, the console says it is empty
This is my code and console result
Are there any errors?
html:
<body>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-remote-config.js"></script>
<script>
var firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
const remoteConfig = firebase.remoteConfig();
var version = remoteConfig.getValue("version");
console.log('version', version);
</script>
</body>
console result
You need to fetch and activate values before call remoteConfig.getValue("version");
remoteConfig.fetchAndActivate()
.then(() => {
var version = remoteConfig.getValue("version");
console.log('version', version);
})
.catch((err) => {
console.log(err);
});
https://firebase.google.com/docs/remote-config/get-started?platform=web#fetch-and-activate-values_1

Firebase initialization

I am using Firebase for the back-end of my app, my firebase configuration looks like :
const firebaseConfig = {
apiKey: 'xx',
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
}
firebase.initializeApp(firebaseConfig)
my question is what if i some configuration data is incorrect.
So how to check if my Firebase database is initialized correctly ? thanks
You can write a test case to check if your configuration is valid.
const getPost = async () => {
const snapshot = await firestore.collection('Posts').get();
const myPosts = snapshot.docs.map(collectIdsAndDocs);
console.log(myPosts);
setPosts({ myPosts });
};
const createPost = async (post) => {
const docRef = await firestore.collection('Posts').add(post);
const doc = await docRef.get();
console.log(doc);
};
createPost({ Title: 'My First Post', Content: 'My content' });
getPost();

PWA foreground push notifications

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

Firebase onMessage is not triggered

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

Categories