Reputation: 135
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
Upvotes: 7
Views: 5682
Reputation: 505
Try to user new version firebase https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging#gettoken
messaging.getToken({
serviceWorkerRegistration: registration,
vapidKey: keyPair
}).then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
Upvotes: 0
Reputation: 3175
I had a similar crazy idea to your answer:
if (!firebase.apps[0]) {
firebase.initializeApp(config);
}
I found that it's better to use firebase.initializeApp(config)
than navigator.serviceWorker.register
. It can be called multiple times without having to worry about whether there is a service worker loaded. Just put this on every page in your app:
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
}
firebase.initializeApp(config);
Upvotes: 1
Reputation: 135
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
Upvotes: 2