简体   繁体   中英

Firebase cloud messaging: Cannot receive notification in React-js

Firebase version: 9.6.6

firebase-messaging.js - inside a src folder

import firebase from "firebase/compat";
import "firebase/messaging";

const firebaseConfig = {
    //api
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

export const requestForToken = async () => {
    const swRegistration = await navigator.serviceWorker.register(`${process.env.PUBLIC_URL}/firebase-messaging-sw.js`);

    const token = await messaging.getToken({
        serviceWorkerRegistration: swRegistration,
    });

    return token;
};

export const onMessageListener = () =>
    new Promise((resolve) => {
        messaging.onMessage((payload) => {
            resolve(payload);
        });
    });

firebase-messaging-sw.js - inside a public folder

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

const firebaseApp = initializeApp({
    //api
});

const messaging = getMessaging(firebaseApp);

Inside App.js

useEffect(()=> {
        if (!fcm_token) {
            requestForToken()
                .then(r => {
                    console.log("token: ", r);
                    dispatch(setFCMToken(r));
                })
                .catch(error => {
                    console.log("error while receiver fcm token from firebase: ", error)
                });
        } else {
            console.log("fcm token: ", fcm_token);
        }
    }, [])

onMessageListener()
        .then(value => console.log("notification msg: ", value))
        .catch(err => console.log("error: ", err))

When I run the project

Failed to register a ServiceWorker for scope ('http://localhost:3000/build/') 
with script ('http://localhost:3000/build/firebase-messaging-sw.js'): 
ServiceWorker script evaluation failed

this error shows up, even though the code is correct according to documentation.

Error persists even if I change the way I import inside firebase-messaging-sw.js file to "importScripts(' ')". Only after removing everything in firebase-messaging-sw.js file, that error do not show up and I can receive the FCM token.

However, when I send test messages from firebase console to FCM token received in my react app, no messages are showing up in console.

Question: How should I change my code to be able to receive notifications and show them in console or as a notification in browser.

If you're using latest version there is alittle bit modifications in registering service worker file, this is complete process of notification configuration

  1. register service worker as below in your service worker file:

     export const registerServiceWorker = () => { if ('serviceWorker' in navigator) { navigator.serviceWorker.register('firebase-messaging-sw.js').then(function (registration) { return registration.scope; }).catch(function (err) { return err; }); }

    };

  2. import service worker, and call function in your index.js File:

 import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { registerServiceWorker } from './serviceWorker'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); registerServiceWorker();

After this configuration, you will see fire base notification in console, and if firebase-messaging.js file is configured well with no error, your feature will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM