Now I am developing a Web application that needs to use the live-notification feature. I am using Google Firebase's Cloud Messaging service. I can successfully register the service and retrieve the token value using JavaScript. But when I push the message from the REST Client, my platform is not triggering the onMessage event.
This is my full code.
<html>
<head>
<title>FCM</title>
</head>
<body>
<h1>This is the FCM</h1>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.1/firebase-functions.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xxx",
authDomain: "fcm-web-testing.firebaseapp.com",
databaseURL: "https://fcm-web-testing.firebaseio.com",
projectId: "fcm-web-testing",
storageBucket: "fcm-web-testing.appspot.com",
messagingSenderId: "xxxx"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission().then(function(){
console.log(messaging.getToken());
return messaging.getToken();
}).then(function(token){
//I get the token here. I use this token to push the notification
console.log(token);
})
.catch(function(err){
alert('Permission denied');
})
messaging.onMessage(function(payload){
//I am expecting to trigger this event when I push the message using the REST client
alert('Message ' + payload)
})
</script>
</body>
</html>
I commented out in the code to highlight what I am expecting to get. I can retrieve the token which I commented in the code. When I get the token, I push the message from the REST client like this.
My request body is something like this
{
"to" : "dJA57nVCZ7A:APA91bFFaYODxZQ4tbyy6RupRvH-jhmM1xh8F3iBQ1BWwdnvHA-dbB50cY1OyYNLpNhZLIKZm7Aqs4nTnQDsd2sExvNIglAeMSw3VLDXGjgaeqBEYFgz6PqbOJIS0Qki6m9XQ931H1xt",
"notification" : {
"body" : "SOMETHING",
"title" : "SOMETHING"
},
"data" : {
"message" : "This is data message"
}
}
As you can see I pass the token retrieved previously to the request body. I also passed server key in the header as well. Post request was successful. I got the following response message.
But on successful request, the event in the Javascript code should be fired.
messaging.onMessage(function(payload){
//I am expecting to trigger this event when I push the message using the REST client
alert('Message ' + payload)
})
But, it was not triggered. Actually, it is supposed to be trigged after the successful post request has been made. What is wrong with or missing in my code?
