quickstart-js: messaging.getToken() not working as expected on Google Chrome
Hi
I’m trying to ensure that I’ll be able to get an fcm device token from firebase whenever I request one via messaging.getToken()
.
When I test getting an fcm device token on page refresh on firefox, it works every single time without fail and I receive a token in my callback function.
On the other hand with Google Chrome, its a completely different story, I only manage to receive a token intermittently. My code stops running at the point where I print in the console “Notification permission granted”. No error messages from the catch block, nada.
Upon further investigation, I found that the function messaging.getToken()
does not return a token i.e. it was undefined, again, this only happens when I use Google Chrome.
Here’s my code:
firebase-initjs
var firebaseConfig = {
apiKey: "api-key-here",
authDomain: "domain-here",
databaseURL: "data-base-url-here",
projectId: "project-id",
storageBucket: "storage-bucket",
messagingSenderId: "sender-id-here",
appId: "app-id-here"
};
console.log(firebase);
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
// Request for permission
Notification.requestPermission()
.then((permission) => {
console.log('Notification permission granted.');
console.log(permission);
//code stops running here on google chrome
messaging.getToken()
.then((currentToken) => {
if (currentToken) {
console.log('Token: ' + currentToken);
sendTokenToServer(currentToken);
var data = { newToken: currentToken };
var url = "/Account/UpdateFirebaseToken";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
dataType: "text",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (data, status, jqXHR) {
console.log("successfully retrieved token:", data, status, jqXHR);
},
error: function (jqXHR, status, err) {
console.log(err);
},
complete: function (jqXHR, status) {
console.log("request complete");
}
});
} else {
//doesn't reach here
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
}
})
.catch(function (err) {
//doesn't reach here either
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
//});
messaging.onMessage(function (payload) {
console.log("Notification 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);
});
});
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') == 1;
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/6.2.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.2.3/firebase-messaging.js');
var config = {
apiKey: "AIzaSyAuTwe4msvCy_UcPHy_ut6CGkJjg0trm9s",
authDomain: "loyalty-app-c011b.firebaseapp.com",
messagingSenderId: "600104612393",
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
var dataFromServer = JSON.parse(payload.data.notification);
var notificationTitle = dataFromServer.title;
var notificationOptions = {
body: dataFromServer.body,
icon: dataFromServer.icon,
data: {
url: dataFromServer.url
}
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
self.addEventListener("notificationclick", function (event) {
var urlToRedirect = event.notification.data.url;
event.notification.close();
event.waitUntil(self.clients.openWindow(urlToRedirect));
});
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 4
- Comments: 15 (3 by maintainers)
Any updates on this issue? I’m having the same problem
use messaging.getToekn({ vapidKey: <YOUR_VAPID_KEY_FROM_CLOUD_CONSOLE> }) and you get a token that works fine.