Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase JS - getToken() does not return a token

I have the following code, based on Google's Documentation:

var config = {
    apiKey: "XX",
    authDomain: "XX",
    databaseURL: "XX",
    storageBucket: "XX",
    messagingSenderId: "XX"
};
firebase.initializeApp(config);

const messaging = firebase.messaging();

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

Strangely enough, the then function of messaging.getToken() is never called. The console does display Notification permission granted., but after that, it stays quiet (i.e. I don't get any errors either).

Am I doing something wrong?

EDIT: It should be noted that I'm trying to implement this in a Chrome extension.

like image 377
TheLeonKing Avatar asked Oct 25 '16 12:10

TheLeonKing


3 Answers

For me, the clue was to run client and api on HTTPS with self-generated localhost SSL certificate. Then, my getToken() started resolving.

It's even in documentation:

The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites.

It would be helpful if getToken() would reject in this situation instead of just hanging forever.

like image 90
Paweł O. Avatar answered Sep 28 '22 03:09

Paweł O.


I have the same problem, and I spend more than 6hours to solve this problem. You need to create dummy "firebase-messaging-sw.js"(empty file) file in home directory.

My html page location is "http://localhost:56050/Notification/index.html"
and my firebase-messaging-sw.js is "http://localhost:56050/firebase-messaging-sw.js"

like image 9
Merbin Jo Avatar answered Nov 12 '22 18:11

Merbin Jo


After I made a change to my "firebase-messaging-sw.js" script, I found that the "messaging.getToken().then(function(currentToken) {" wouldn't return.

I went into Chrome's "Developer Tools" -> "Applications" -> "Service Workers" (as shown in the image below) and Unregistered the old service worker. After that the "messaging.getToken().then(function(currentToken) {" returned okay.

Another issue that I had was that I initially had two Firebase projects on my one domain name, which isn't permitted due to limitations with SSL certificates.

Stop and Unregister an existing Firebase Messaging Service Worker in Chrome's Developer Tools

like image 3
Stephen Bridgett Avatar answered Nov 12 '22 18:11

Stephen Bridgett