Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase messaging error: using service worker before get token

I'm trying to use FCM with angularjs, so after initializing firebase I wrote the following code:

messaging = firebase.messaging();
$window.navigator.serviceWorker.register($rootScope.app.base_url + '/app/lib/firebaseCustomWorker.js')
.then(function(registration) {
    messaging.useServiceWorker(registration);
    messaging.requestPermission().then(function(){  
    messaging.getToken()
    .then(function(currentToken) {
        console.log(currentToken);
    })
    .catch(function(err) {
        console.log('An error occurred while retrieving token. ', err);
    });
}).catch(function(err){console.log(err)});

the problem is that the last line sometimes catches an error which appears in console with code "messaging/use-sw-before-get-token" and message that says:

FirebaseError: Messaging: You must call useServiceWorker() before calling getToken() to ensure your service worker is used. (messaging/use-sw-before-get-token).

And as you can see in the code above, I only call getToken() after calling useServiceWorker() and after requestPermission()

I dug into the original firebase-messaging.js file in line 35 but unfortunately didn't get any clue of why this is happening

like image 935
Hassan Ajk Avatar asked Mar 07 '18 10:03

Hassan Ajk


1 Answers

I know this is probably crazy and will backfire but it works.

 .
 .
 .
 if('undefined' !== typeof messaging.b )
      delete(messaging.b);
 messaging.useServiceWorker(registration);
 .
 .
 .

inspired by reading firebase-messaging.js

like image 77
Hassan Ajk Avatar answered Oct 05 '22 22:10

Hassan Ajk