Unable to receive the notification in the app and getting errors
Asked Answered
E

2

1

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)
Egoism answered 16/9, 2021 at 17:7 Comment(0)
C
3

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.

Cragsman answered 16/9, 2021 at 18:47 Comment(14)
Bro, I completely cleared all of my browsing data as well as tried with a fresh new browser too, but still I'm unable to receive the notifications. seems something is wrong there in my message receiving flow. can you please test my code at your end and check that why is it not working? May be you'll be able to understand it in more detail then. Thanks a lot really in advance.Egoism
I will try it tomorrow. But can you just tell me do you have your app in focus when you try it or is it out of focus?Cragsman
It is out of focus because I'm sending the message via firebase console. Now also getting this error: FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('localhost:3000/firebase-cloud-messaging-push-scope') with script ('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)Egoism
This firebase thing is really making me crazy now. I'm fed up and it is not working :(Egoism
Dount you dare to give up on this! We will fix it together. Let me again take a look on it. One thing that could make us problems from start is the way you host your app localy. Have you tried to publish it ona test firebase project and to se how it behaves in production?Cragsman
Bro, thanks a lot for your help. I must say that you are really helpful. I hope it can be fixed. No, actually I didn't try to host it on the firebase hosting server, I'm hosting it locally via express only. :(Egoism
I have updated the answer. It worked on my side.Cragsman
Oh, amazing buddy! It works. thanks a lot. So I see that the only thing which was needed here and I was missing is to use compat packages instead of regular modular ones. As soon as I imported the compat packages, it started working. Thanks for your code bro. However, I don't want to use the old/compat packages, so isn't there any way to use the newer packages in firebase-messaging-sw.js?Egoism
I'm getting errors if I'm using the newer packages in my firebase-messaging-sw.js fileEgoism
There is no downside if you use them in that SW. It won't affect the performance of your app at all. Unfortunately I can't find any example for the SW using the new SDK. Here is the documentation for it: firebase.google.com/docs/cloud-messaging/js/… . Even the official example project uses the compat version github.com/firebase/quickstart-js/blob/master/messaging/…Cragsman
Yes bro, you are absolutely right. I too can't find any examples which uses the newer packages. and I tried to go through the google official example many times before (the same link which you've provided above) and everytime got disappointed to see that they are not updating their examples for newer packages. I don't know why is so. Ok bro, for now I'll use the compat packages only. One more thing, I really appreciate your help and want to connect with you personally if you don't mind. I asure you that I won't disturb you with my questions, only wanted to connect casually. is it possible?Egoism
Sure. That is no problem :) ecronix.comCragsman
Thanks a lot bro. wow, that's a good way to consolidate all our social networks/contact info at one place. amazing.Egoism
"Set the page notification permissions to default and request a completely new token." This solves it for me.Gravy
P
1

-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

Portrait answered 1/2, 2023 at 23:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.