Akash Kakkar
Akash Kakkar

Reputation: 335

Unable to receive the notification in the app and getting errors

My code is there at this repo: https://github.com/akash07k/Clouding.git So, I'm unable to receive the notifications in my app. When I'm sending the notification to the app, then I'm getting the following errors in console:

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)

Upvotes: 1

Views: 2487

Answers (2)

Crypto-Frank
Crypto-Frank

Reputation: 360

-Open Google Chrome DevTools by pressing Ctrl + Shift + I (or Cmd + Option + I on a Mac)

-Click on the Application tab.

-Expand the Storage section in the left-side panel.

-Expand firebase-messaging-database

-Right click on the key-value and delete it

-Refresh your app and the error is gone

Upvotes: 1

Tarik Huber
Tarik Huber

Reputation: 7388

From the previous question context I would recommend to set the page notification permissions to default and request a completely new token. Also make sure to use your vapidKey. But you already wrote that you did that. What could be the issue here is that you still have a token from the wring vapidKey and so you don't get permission to send from your app to that token.

With this code it should work: enter image description here You can see on the bottom the received message.

The html file:

<!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>

The firebase-messaging-sw.js file:

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

It is extremely importand that you change the firebase configs in both files and the vapiKey. Then remove all permissions for notifications where you have hosted your project.

Unregister the curren Firebase SW as he might be corrupted and stuck: enter image description here

Also pls use serve for the local hosting. After that open your side press the button and copy the token here:

enter image description here

After sending your message you won't see a notification because we are handling it on y custom way so you will only see a log like in the first picture.

Upvotes: 3

Related Questions