0

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.

enter image description here

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?

2 Answers 2

1

How do you serve your web app? It must be served over httpS (Description), otherwise the ServiceWorker / Messaging won't work.

Have a look at the Developer Console (Chrome) -> Application -> Service Workers, your SW should appear here.


Edit:

For testing you can also upload your project into firebase hosting. There is a free ssl cert. included. To do so, install the firebase cli (via npm):

npm install -g firebase-tools

Then, first run the login command to log into your google account:

firebase login

and 'init' a new project (like npm init):

firebase init

Deploying then is as easy as typing

firebase deploy

Have a look here for more details.

Sign up to request clarification or add additional context in comments.

3 Comments

Now, it is over http. But localhost. It should work. I will try to fake the https on localhost and try it again.
Hi. Thanks for the suggestion. I could not manage to install ssl for my localhost. So I ended up using Pusher (pusher.com/…) instead. It is even better.
if it solved your problem, please consider marking it as the answer :-)
0

You no need to have https when testing locally. Just http://localhost:<< port>> works fine. If you deploy your site on to a domain(not localhost), then it has to be https to get firebase service worker working.

  1. you will get notification only when the window is minimised/not focused.
  2. if window is in focus, directly onmessage event will be fired.
  3. Try below JSON Posts:

Below push handled by firebase serviceworker internally(if you use firebase hosting) you don't need to handle it with setBackgroundMessageHandler in your sw.

{
  "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1",
    "icon": "firebase-logo.png"
  },
  "to": "ecce7xlo9CA:APA91bEXPT-NCnl9evVE....",
  "priority": "high"
}

Below will not be handled internally, you need to setBackgroundMessageHandler in your sw.

{
  "data":{
    "id": 1,
    "missedRequests": 5,
    "addAnyDataHere": 123
  },
  "to": "ecce7xlo9CA:APA91bEXPT-NCnl9evVE....",
  "priority": "high"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.