messaging.onMessage() (JavaScript) not being called when push notification is sent

Viewed 2260

i found a question similar to that on Stackoverflow but unfortunately it wasn't answered.

I'm trying to send a push notification to Web using FCM. I have set my app server and its working fine when i put the tokens of android devices and notifications are successfully delivered to all the tokens. However, the onMessage() function on the web is not being called when the notification is sent to the web.

My code is:

<script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
       <script>
         // Initialize Firebase
         var config = {
           apiKey: "xxxxxxxxx",
           authDomain: "xxxxxxxx",
           databaseURL: "xxxxxxx",
           projectId: "xxxxxxxxxxxx",
           storageBucket: "xxxxxxxxx",
           messagingSenderId: "xxxxxxxxx"
         };
         firebase.initializeApp(config);

           //Get Token
          const messaging = firebase.messaging();
          messaging.requestPermission()
           .then(function () {
               console.log('Have permission');
               return messaging.getToken();
           })
        .then(function (token) {
            console.log(token);
        })
          .catch(function (err) {
              console.log('Error occurred');
          });

          messaging.onMessage(function (payload) {
              console.log('onMessage', payload);
          })

Code for firebase-messaging-sw.js code:

importScripts('https://www.gstatic.com/firebasejs/4.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.6.0/firebase-messaging.js');

var config = {
apiKey: "xxxxxxxxx",
authDomain: "XXXXXXXXXX",
databaseURL: "XXXXXXXXXX",
projectId: "XXXXXXXXXX",
storageBucket: "XXXXXXXXX",
messagingSenderId: "XXXXXXXXXX"
};

firebase.initializeApp(config);

const messaging = firebase.messaging();

I can't figure out what's wrong.

1 Answers
Related