Error while I want to get token for use firebase cloud message in react

Viewed 49

error picture it said like this its happen after I give the permission for notification

my function

 const requestPermission = ()=>{
  console.log("requesting permission")
  Notification.requestPermission().then(permission=>{
    if (permission === "granted"){
      console.log("permission granted")
      getToken(ms,{vapidKey: "key"})
      .then(currentToken=>{
        if(currentToken){
          console.log("token = ",currentToken)
        }
        else{
          console.log("cannot get token")
        }
      })
    }
    else{
      console.log("didn't get permission")
    }
  })
}
requestPermission()

i use firebase version 9.9.4

and firebase config I think it's find because before these i can use firebase database

and i doc said i need to create firebase-messaging-sw.js empty file in root

so i create it but it's still not work do you guy have any idea?

1 Answers

Create firebase-messaging-sw.js file in public folder and insert this code:

 importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
    console.log('Received background message ', payload);
    // Customize notification here
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
    };

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

Create firebase.js file and insert this code:

    import { initializeApp } from 'firebase/app';
import { getMessaging, getToken,onMessage} from 'firebase/messaging';
// Replace this firebaseConfig object with the congurations for the project you created on your firebase console.

    const firebaseConfig = {
        apiKey: "",
        authDomain: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: "",
        measurementId: ""
    };
    const messaging = null;
    if(window.location.hostname=='localhost' || window.location.hostname=='127.0.0.1' || windows.location.protocol == 'https:'){

    const app = initializeApp(firebaseConfig);


    const messaging = getMessaging();
    }

    export const requestForToken = () => {
        if(window.location.hostname=='localhost' || window.location.hostname=='127.0.0.1' || windows.location.protocol == 'https:'){
            return getToken(messaging, { vapidKey: "key" })
            .then((currentToken) => {
                if (currentToken) {
                    console.log('current token for client: ', currentToken);
                    localStorage.setItem('fcm_token',currentToken);
                    // Perform any other neccessary action with the token
                } else {
                    // Show permission request UI
                    console.log('No registration token available. Request permission to generate one.');
                }
            })
            .catch((err) => {
                console.log('An error occurred while retrieving token. ', err);
            });
        } else {
            console.log('Unsopperted browser')
        }
        
    };

    export const onMessageListener = () =>{
        if(window.location.hostname=='localhost' || window.location.hostname=='127.0.0.1' || windows.location.protocol == 'https:'){
            return new Promise((resolve) => {
                onMessage(messaging, (payload) => {
                    console.log("payload", payload)
                    resolve(payload);
                });
            });
        } else {
            new Promise((resolve) => {
                resolve('Unsopperted browser');
            });
        }
        
    }

FCM works only localhost or https request!

Related