mardi 8 mai 2018

FCM Web Push Notifications - can't obtain token

This is really nocking me out after spending with such easy thing ver two days:

I'm trying to implement FCM Web browser Push Notifications and I went through the google docs several times as well as I watched all official videos on youtube. It is really easy to get the Token but for some reason it crashes in Firebase's JS code.

Here is my HTML/JS code here:

<html>
    <head>
        <title>Web Push Test 2</title>
        <script src="/vendors/jquery/dist/jquery.min.js"></script>
        <script src="https://www.gstatic.com/firebasejs/4.13.0/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/4.13.0/firebase-messaging.js"></script>
    </head>
    <body>
        <button type="button" id="subscribe">Subscribe</button><br />
        <script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>       
        <script>
              var config = {
                apiKey: "AIzaSyBgYGotOm09UkhERqVPriV1XNhymxracno",
                authDomain: "******-b6f9c.firebaseapp.com",
                databaseURL: "https://******-b6f9c.firebaseio.com",
                projectId: "*******-b6f9c",
                storageBucket: "******-b6f9c.appspot.com",
                messagingSenderId: "333638181210"
              };
              firebase.initializeApp(config);

        if ('Notification' in window) {
            console.log("Notification is in window.");
            var messaging = firebase.messaging();
            messaging.usePublicVapidKey("BE0MvVZ0zyTYGmeNIdj4A8XZZ50OKaZL90xmXbIVfufcMuPb0lAUC99426aBPrAEPHAWYeMbOTpHbcM3OiySEcs");
            messaging.onMessage(function(payload) {
              console.log("Message received. ", payload);
            });

            messaging.onTokenRefresh(function() {
              messaging.getToken().then(function(refreshedToken) {
                console.log('Token refreshed.');
                setTokenSentToServer(false);
                sendTokenToServer(refreshedToken);
              }).catch(function(err) {
                console.log('Unable to retrieve refreshed token ', err);
                showToken('Unable to retrieve refreshed token ', err);
              });
            });

            if (Notification.permission === 'granted') {
                console.log("Permission is granded.");
                subscribe();
            }

            $('#subscribe').on('click', function () {
                console.log("Subscribe fired.");
                subscribe();
            });
        }

        function subscribe() {
            messaging.requestPermission().then(function() {
                  console.log('Notification permission granted.');            
                  messaging.getToken().then(function(currentToken) {
                    if (currentToken) {
                      sendTokenToServer(currentToken);
                    } else {
                      console.log('No Instance ID token available. Request permission to generate one.');
                      setTokenSentToServer(false);
                    }
                  }).catch(function(err) {
                    console.log('An error occurred while retrieving token. ', err);
                    showToken('Error retrieving Instance ID token. ', err);
                    setTokenSentToServer(false);
                  });
            }).catch(function(err) {
              console.log('Unable to get permission to notify.', err);
            });
        }

        window.is_sentToServer = false
        function setTokenSentToServer(sent) {
            window.is_sentToServer = sent
        }

        function showToken(currentToken) {
          console.log('Token: '+currentToken);
        }

        function sendTokenToServer(currentToken) {
            $.post('/?c=push&a=save_subscription', {token: currentToken}, function(data){
                console.log('Token added...');
                setTokenSentToServer(true);
            });
        }
    </script>
</body>

When I run the page, I get the following error:

An error occurred while retrieving token.  TypeError: Cannot read property 'buffer' of undefined

And the crash point of firebase JS is here:

https://www.gstatic.com/firebasejs/messaging/dist/index.esm.js

function isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails) {
if (!isArrayBufferEqual(publicVapidKey.buffer, tokenDetails.vapidKey.buffer)) {
    return false;
}
var isEndpointEqual = pushSubscription.endpoint === tokenDetails.endpoint;
var isAuthEqual = isArrayBufferEqual(pushSubscription.getKey('auth'), tokenDetails.auth);
var isP256dhEqual = isArrayBufferEqual(pushSubscription.getKey('p256dh'), tokenDetails.p256dh);
return isEndpointEqual && isAuthEqual && isP256dhEqual;

}

So as I can understand so far - the tokenDetails.vapidKey variable is undefined, that's is why it can't read the buffer size, but the question is - why?

I double checked that all my provided Keys are valid but can't figure out what could be wrong here...

Many thanks to anyone who could help me out with this

I'm running that test on localhost as it is shown in original YouTube tutorial and I didn't forget to create the firebase-messaging-sq.js which looks like this:

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

var config = {
  apiKey: "AIzaSyBgYGotOm09UkhERqVPriV1XNhymxracno",
  authDomain: "*****-b6f9c.firebaseapp.com",
  databaseURL: "https://******-b6f9c.firebaseio.com",
  projectId: "*******-b6f9c",
  storageBucket: "*****-b6f9c.appspot.com",
  messagingSenderId: "333638181210"
};
firebase.initializeApp(config);

const messaging = firebase.messaging();

messaging.usePublicVapidKey("BE0MvVZ0zyTYGmeNIdj4A8XZZ50OKaZL90xmXbIVfufcMuPb0lAUC99426aBPrAEPHAWYeMbOTpHbcM3OiySEcs");

messaging.setBackgroundMessageHandler(function (payload) {
  console.log('Handling background message ', payload);

  return self.registration.showNotification(payload.notification.title, {
    body: payload.notification.body
  });
});




Aucun commentaire:

Enregistrer un commentaire