Search code examples
javascriptfirebasepush-notificationfirebase-cloud-messaging

Firebase Cloud Messaging Token is undefined upon website loading


I just setup Firebase Cloud Messaging for my website.

Everything works super fine.

However, after the user has granted to receive Notifications the following code does not show the FCM token after the site has been reloaded:

<script>
  var config = {
    apiKey: "XXX",
    ....
  };
  firebase.initializeApp(config);
  const messaging = firebase.messaging();

  ...

  function fcm_get_fcm_push_token() {
    messaging.getToken().then(function(fcmToken){ return fcmToken }); // <-- returns undefined
  }

  function print_fcm_token() {
    console.log(fcm_get_fcm_push_token()); //prints undefined
  }

  window.onload = print_fcm_token;
</script>

As said, the notifications are granted. However, the token is not returned.

Why is that?


Solution

  • This is probably a problem related to asynchrony. The callback you are providing to the then doesn't actually change the value of your container function returns, as it is not returning anything. You have to return the promise and then wait for it to resolve:

    function fcm_get_fcm_push_token() {
        return messaging.getToken();
    }
    
    function print_fcm_token() {
        fcm_get_fcm_push_token().then(console.log);
    }
    

    Or maybe the async/await approach:

    function fcm_get_fcm_push_token() {
        return messaging.getToken();
    }
    
    async function print_fcm_token() {
        const token = await fcm_get_fcm_push_token();
        console.log(token);
    }
    

    And i think you dont need the wrapper function:

    async function print_fcm_token() {
        const token = await messaging.getToken();
        console.log(token);
    }