【问题标题】:Getting many errors in firebase cloud messaging app在 Firebase 云消息传递应用程序中出现许多错误
【发布时间】:2021-09-15 12:23:02
【问题描述】:

更新: 包含整个代码的存储库如下: https://github.com/akash07k/Clouding 所以,我正在开发我的 FCM 应用程序,一旦我允许应用程序的通知,我就会收到很多错误。 第一个错误是关于“onTokenRefresh”不是一个函数。 我对每条错误消息进行了很多搜索,但找不到任何线索。 如果有人可以帮助我,我将不胜感激。 我在下面提供了错误和整个代码: 以下是错误:

(index):73 Uncaught ReferenceError: onTokenRefresh is not defined
    at initFirebaseMessagingRegistration ((index):73)
    at (index):31
(index):46 Got notification permission
(index):55 Didn't get notification permission TypeError: Cannot read properties of undefined (reading 'vapidKey')
    at updateVapidKey (updateVapidKey.ts:27)
    at getToken$1 (getToken.ts:42)
    at getToken (api.ts:114)
    at (index):47
(index):65 Didn't get notification permission FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
    at registerDefaultSw (registerDefaultSw.ts:43)
    at async updateSwReg (updateSwReg.ts:28)
    at async getToken$1 (getToken.ts:43)
Error
(index):73 Uncaught ReferenceError: onTokenRefresh is not defined
    at initFirebaseMessagingRegistration ((index):73)
    at (index):31
(index):46 Got notification permission
(index):55 Didn't get notification permission TypeError: Cannot read properties of undefined (reading 'vapidKey')
    at updateVapidKey (updateVapidKey.ts:27)
    at getToken$1 (getToken.ts:42)
    at getToken (api.ts:114)
    at (index):47
Error
firebase-messaging-sw.js:4 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js' failed to load.
    at http://localhost:3000/firebase-messaging-sw.js:4:1
(index):65 Didn't get notification permission FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
    at registerDefaultSw (registerDefaultSw.ts:43)
    at async updateSwReg (updateSwReg.ts:28)
    at async getToken$1 (getToken.ts:43)

代码: index.html:

<!DOCTYPE html>
<html lang="en">

<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.com/firebasejs/9.0.2/firebase-app.js";
        import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
        import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/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.com",
            projectId: "clouding-aa740",
            storageBucket: "clouding-aa740.appspot.com",
            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 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: "293kfk" })
                .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;
            });
            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>Welcome to Clouding</h1>
        <div id="token" style="color:lightblue" role="alert"></div>
        <div id="message" style="color:lightblue" role="alert"></div>
        <div id="notification" style="color:green" role="alert"></div>
        <div id="error" style="color:red" role="alert"></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>

firebase-messaging-sw.js:

// Import and configure the Firebase SDK

// Import the functions you need from the SDKs you need
importScripts('https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js');

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/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.com",
  projectId: "clouding-aa740",
  storageBucket: "clouding-aa740.appspot.com",
  messagingSenderId: "1059589787087",
  appId: "1:1059589787087:web:cdd636057d2a921ccdd6ba",
  measurementId: "G-CD2BEK39LZ"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const messaging = getMessaging(app);

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// Keep in mind that FCM will still show notification messages automatically 
// and you should use data messages for custom notifications.
// For more info see: 
// https://firebase.google.com/docs/cloud-messaging/concept-options
messaging.onBackgroundMessage(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging


    【解决方案1】:

    onTokenRefresh 在新的 Firebase SDK 9 版本中不存在。我也在API References 中搜索过它或替代品,但找不到。

    您能否取消对onTokenRefresh 部分的评论,看看是否至少有一些错误消失了。

    您也不需要自己请求许可。 getToken 会自动完成。

    更新:

    它对我来说是如何工作的。从firebase-messaging-sw.js 中删除所有代码(至少现在是这样),但保留空文件。并放入有效的 Firebase Cofnig 数据(也是有效的vapidKey):

    这是我的一个项目的配置,它成功了:

    <!DOCTYPE html>
    <html lang="en">
    
    <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.com/firebasejs/9.0.2/firebase-app.js";
            import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
            import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js";
            // TODO: Add SDKs for Firebase products that you want to use
            // https://firebase.google.com/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: 'AIzaSyBQAmNJ2DbRyw8PqdmNWlePYtMP0hUcjpY',
                authDomain: 'react-most-wanted-3b1b2.firebaseapp.com',
                databaseURL: 'https://react-most-wanted-3b1b2.firebaseio.com',
                projectId: 'react-most-wanted-3b1b2',
                storageBucket: 'react-most-wanted-3b1b2.appspot.com',
                messagingSenderId: '258373383650',
                appId: '1:258373383650:web:b49ad5dd28da999a',
            };
            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() {
    
                // Don't forget your vapidKey here
                getToken(messaging, { vapidKey: "BEthk1-Qmoh9opZbi1AUZpxANTu6djVRDph4MLpyO2Qk6Dglm1Sa8Yt_pYi4EhYi3Tj-xgLqUktlbNuP_RP6gto" })
                    .then((t) => {
                        tokenElement.innerHTML = "Token is " + t;
                    })
                    .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;
                });
            }
    
        </script>
    
    </head>
    
    <body>
        <main>
            <h1>Welcome to Clouding</h1>
            <div id="token" style="color:lightblue" role="alert"></div>
            <div id="message" style="color:lightblue" role="alert"></div>
            <div id="notification" style="color:green" role="alert"></div>
            <div id="error" style="color:red" role="alert"></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>
    

    这是令牌:

    【讨论】:

    • 兄弟,我删除了 onTokenRefresh 部分,该错误现在消失了。但其他错误仍然存​​在实际上可悲的是,谷歌的 firebase 快速入门示例 repo 不包含较新的 (moduler) sdk 的代码。
    • 您能否用新的错误消息更新问题。
    • tarik-huber 错误与我在问题中所说的相同。只有与 onRefreshToken 相关的错误消失了
    • 你能不能同时删除`Notification.requestPermission()`和它的其他部分。您是否还可以确保您尝试使用的域的通知权限被重置为默认值或被接受。
    • 我做了这个兄弟,但同样的错误。我觉得我的 firebase-messaging-sw.js 有问题,但无法发现任何问题。我应该在 repo 或文件中分享完整的代码,以便您查看吗?
    猜你喜欢
    • 2020-09-04
    • 2020-12-31
    • 2023-04-01
    • 2017-02-25
    • 2022-12-30
    • 2018-09-30
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多