admin管理员组

文章数量:1429858

So I'm working on a firebase cloud messaging web app and getting the error:

Error: TypeError: messaging.getToken is not a function

I tried a lot to troubleshoot it, searched on google too, but no luck. I'd be thankful if someone can help me.

The same code is working fine in the official google example. Below is the line where I'm getting this error:

            return messaging.getToken();

Below is the whole code:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clouding</title>
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from ".0.2/firebase-app.js";
        import { getAnalytics } from ".0.2/firebase-analytics.js";
        import { getMessaging } from ".0.2/firebase-messaging.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // 

        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
            apiKey: "AIzaSyDOVN1qOGzsD6AI-2jA05LpfQIJ5aoCuD4",
            authDomain: "clouding-aa740.firebaseapp",
            projectId: "clouding-aa740",
            storageBucket: "clouding-aa740.appspot",
            messagingSenderId: "1059589787087",
            appId: "1:1059589787087:web:cdd636057d2a921ccdd6ba",
            measurementId: "G-CD2BEK39LZ"
        };
        window.addEventListener("click", (e) => {
            switch (e.target.id) {
                case "btnPermissions":
                    initFirebaseMessagingRegistration();
                    break;
            }
        });
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        //        const analytics = getAnalytics(app);
        const messaging = getMessaging(app);


        function initFirebaseMessagingRegistration() {

            Notification.requestPermission()
                .then(function () {
                    messageElement.innerHTML = "Got notification permission";
                    console.log("Got notification permission");
                    return messaging.getToken();
                })
                .then(function (token) {
                    // print the token on the HTML page
                    tokenElement.innerHTML = "Token is " + token;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            // Don't forget your vapidKey here
            getToken(messaging, { vapidKey: "publicVapidKey" })
                .then((t) => {
                    tokenElement.innerHTML = "Token is " + r;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            onMessage(messaging, (payload) => {
                console.log("Message received. ", JSON.stringify(payload));
                notificationElement.innerHTML =
                    notificationElement.innerHTML + " " + payload.data.notification;
            });
            messaging.onTokenRefresh(function () {
                messaging.getToken()
                    .then(function (refreshedToken) {
                        console.log('Token refreshed.');
                        tokenElement.innerHTML = "Token is " + refreshedToken;
                    }).catch(function (err) {
                        errorElement.innerHTML = "Error: " + err;
                        console.log('Unable to retrieve refreshed token ', err);
                    });
            });
            console.log("clicked");
        }

    </script>

</head>

<body>
    <main>
        <h1>Wele to Clouding</h1>
        <div id="token" style="color:lightblue"></div>
        <div id="message" style="color:lightblue"></div>
        <div id="notification" style="color:green"></div>
        <div id="error" style="color:red"></div>
        <script>
            messageElement = document.getElementById("message")
            tokenElement = document.getElementById("token")
            notificationElement = document.getElementById("notification")
            errorElement = document.getElementById("error")
        </script>
        <button id="btnPermissions">Enable Firebase Messaging</button>

    </main>

</body>

</html>

So I'm working on a firebase cloud messaging web app and getting the error:

Error: TypeError: messaging.getToken is not a function

I tried a lot to troubleshoot it, searched on google too, but no luck. I'd be thankful if someone can help me.

The same code is working fine in the official google example. Below is the line where I'm getting this error:

            return messaging.getToken();

Below is the whole code:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clouding</title>
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic./firebasejs/9.0.2/firebase-app.js";
        import { getAnalytics } from "https://www.gstatic./firebasejs/9.0.2/firebase-analytics.js";
        import { getMessaging } from "https://www.gstatic./firebasejs/9.0.2/firebase-messaging.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google./docs/web/setup#available-libraries

        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
            apiKey: "AIzaSyDOVN1qOGzsD6AI-2jA05LpfQIJ5aoCuD4",
            authDomain: "clouding-aa740.firebaseapp.",
            projectId: "clouding-aa740",
            storageBucket: "clouding-aa740.appspot.",
            messagingSenderId: "1059589787087",
            appId: "1:1059589787087:web:cdd636057d2a921ccdd6ba",
            measurementId: "G-CD2BEK39LZ"
        };
        window.addEventListener("click", (e) => {
            switch (e.target.id) {
                case "btnPermissions":
                    initFirebaseMessagingRegistration();
                    break;
            }
        });
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        //        const analytics = getAnalytics(app);
        const messaging = getMessaging(app);


        function initFirebaseMessagingRegistration() {

            Notification.requestPermission()
                .then(function () {
                    messageElement.innerHTML = "Got notification permission";
                    console.log("Got notification permission");
                    return messaging.getToken();
                })
                .then(function (token) {
                    // print the token on the HTML page
                    tokenElement.innerHTML = "Token is " + token;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            // Don't forget your vapidKey here
            getToken(messaging, { vapidKey: "publicVapidKey" })
                .then((t) => {
                    tokenElement.innerHTML = "Token is " + r;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            onMessage(messaging, (payload) => {
                console.log("Message received. ", JSON.stringify(payload));
                notificationElement.innerHTML =
                    notificationElement.innerHTML + " " + payload.data.notification;
            });
            messaging.onTokenRefresh(function () {
                messaging.getToken()
                    .then(function (refreshedToken) {
                        console.log('Token refreshed.');
                        tokenElement.innerHTML = "Token is " + refreshedToken;
                    }).catch(function (err) {
                        errorElement.innerHTML = "Error: " + err;
                        console.log('Unable to retrieve refreshed token ', err);
                    });
            });
            console.log("clicked");
        }

    </script>

</head>

<body>
    <main>
        <h1>Wele to Clouding</h1>
        <div id="token" style="color:lightblue"></div>
        <div id="message" style="color:lightblue"></div>
        <div id="notification" style="color:green"></div>
        <div id="error" style="color:red"></div>
        <script>
            messageElement = document.getElementById("message")
            tokenElement = document.getElementById("token")
            notificationElement = document.getElementById("notification")
            errorElement = document.getElementById("error")
        </script>
        <button id="btnPermissions">Enable Firebase Messaging</button>

    </main>

</body>

</html>
Share Improve this question edited Sep 15, 2021 at 14:17 Frank van Puffelen 601k85 gold badges890 silver badges860 bronze badges asked Sep 15, 2021 at 8:59 Akash KakkarAkash Kakkar 3356 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Got it, I had to import getToken method also. Below is the new snippet which I should have wrote:

import { getMessaging, getToken } from "https://www.gstatic./firebasejs/9.0.2/firebase-messaging.js";

instead of:

import { getMessaging } from "https://www.gstatic./firebasejs/9.0.2/firebase-messaging.js";
import { getMessaging, getToken } from "https://www.gstatic./firebasejs/9.0.2/firebase-messaging.js";

const messaging = getMessaging(app);
    // Add the public key generated from the console here.
    getToken({vapidKey: "BBxqsbhYwDSfJ..."});

https://stackoverflow./a/70046707/5681567 Check out the link given. Same problem was arises with react native. Try this kind of thing

messaging ().getToken()

本文标签: javascriptTypeError messaginggetToken is not a functionStack Overflow