无法在应用程序中接收通知并获取错误

Unable to receive the notification in the app and getting errors(无法在应用程序中接收通知并获取错误)
本文介绍了无法在应用程序中接收通知并获取错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在此回购中: https://github.com/akash07k/Clouding.git 因此,我无法在我的应用程序中接收通知。 当我向应用程序发送通知时,控制台中出现以下错误:

fcmregistrations.goo…45qFPDOp7C-LYs1JN:1 Failed to load resource: the server responded with a status of 404 ()
Warning
token-manager.ts:67 FirebaseError: Messaging: A problem occurred while unsubscribing the user from FCM: FirebaseError: Messaging: A problem occurred while unsubscribing the user from FCM: Requested entity was not found. (messaging/token-unsubscribe-failed). (messaging/token-unsubscribe-failed).
    at requestDeleteToken (requests.ts:143)
    at async getTokenInternal (token-manager.ts:61)

推荐答案

从前面的question上下文中,我建议将页面通知权限设置为默认并请求一个全新的令牌。还要确保使用您的vapidKey。但你已经写过你这么做了。这里可能出现的问题是,您仍然拥有来自WRINGvapidKeytoken,因此您没有获得从您的应用程序向该令牌发送的权限。

使用此代码,它应该可以工作: 您可以在底部看到收到的消息。

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
//CHANGE HERE
        const firebaseConfig = {
      apiKey: "AIzaSyCADVGUqs4tNdem8OMOhDO0i3G0wjQiCB4",
            authDomain: "extension-tester.firebaseapp.com",
            databaseURL: "https://extension-tester.firebaseio.com",
            projectId: "extension-tester",
            storageBucket: "extension-tester.appspot.com",
            messagingSenderId: "230563136927",
            appId: "1:230563136927:web:4c789d9b12e93317cf69aa"
        };
        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
// CHANGE HERE
            getToken(messaging, { vapidKey: "BAqU95FyfIh8ikX7gecF3fTd6vyrXpS2JU8Urvr8KpNFyzFOiiR2dHCy_TJHftplF-pXvM7ERbNkwczszx4PNPs" })
                .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>

firebase-messaging-sw.js文件:

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts(
  "https://www.gstatic.com/firebasejs/9.0.1/firebase-app-compat.js"
);
importScripts(
  "https://www.gstatic.com/firebasejs/9.0.1/firebase-messaging-compat.js"
);
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object

//CHANGE HERE
firebase.initializeApp({
  apiKey: "AIzaSyCADVGUqs4tNdem8OMOhDO0i3G0wjQiCB4",
  authDomain: "extension-tester.firebaseapp.com",
  databaseURL: "https://extension-tester.firebaseio.com",
  projectId: "extension-tester",
  storageBucket: "extension-tester.appspot.com",
  messagingSenderId: "230563136927",
  appId: "1:230563136927:web:4c789d9b12e93317cf69aa",
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

// 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);
});

非常重要的一点是,您必须同时更改文件和vapiKey中的Firebase配置。然后删除您托管项目的通知的所有权限。

注销Curren Firebase软件,因为它可能已损坏和卡住:

也请使用serve进行本地托管。之后,打开您的侧面,按下按钮并将令牌复制到此处:

发送邮件后,您将看不到通知,因为我们正在以y自定义方式处理它,所以您只会看到第一张图片中所示的日志。

这篇关于无法在应用程序中接收通知并获取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)