Web推送通知在使用Firebase的React JS中不起作用

问题描述

我试图在我的REact js项目中使用Firebase实施Web推送通知

Index.js

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import './App.css';
import { createStore,compose,applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension/developmentOnly";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import {messaging} from "./config/FirebaseConfig"

import App from "./App";
import * as serviceWorker from "./serviceWorker";
import rootReducer from "./reducers/rootReducer";

const store = createStore(
  rootReducer,composeWithDevTools(applyMiddleware(thunk))
);

if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register(`./firebase-messaging-sw.js`)
    .then(function(registration) {
      messaging.useServiceWorker(registration); 
      console.log("Registration successful,scope is:",registration.scope);
    })
    .catch(function(err) {
      console.log("Service worker registration Failed,error:",err);
    });
}

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,document.getElementById("root")
);

serviceWorker.register();

以上文件是位于src文件夹中的主要源文件。 我添加 firebase-messaging-sw.js ,如下所示:

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

firebase.initializeApp({
        messagingSenderId: "XXXXXX",});

const messaging = firebase.messaging();

messaging.usePublicvapidKey("XXXXXXXXXXXXXXXXXXXXX")

messaging.setBackgroundMessageHandler(function(payload) {
  const promiseChain = clients
    .matchAll({
      type: "window",includeUncontrolled: true
    })
    .then(windowClients => {
      for (let i = 0; i < windowClients.length; i++) {
        const windowClient = windowClients[i];
        windowClient.postMessage(payload);
      }
    })
    .then(() => {
      return registration.showNotification("my notification title");
    });
  return promiseChain;
});

self.addEventListener('notificationclick',function(event) {
  // do what you want
  // ...
});

我在Main组件的amount方法添加了请求权限代码,如下所示:

componentDidMount()
{
    messaging.requestPermission()
      .then(async function() {
          const token = await messaging.getToken();
          console.log("token",token)
      })
      .catch(function(err) {
          console.log("d to get permission to notify.",err);
      });
      navigator.serviceWorker.addEventListener("message",(message) => console.log(message));
      messaging.onMessage((payload) => console.log('Message received. ',payload));

      const fetchOptions = {
          method: "POST",headers: {
            "Authorization": "key=l9oalOyzXcU-NqCI4LZyVrLuF3X3_4tiOHpMUYK_AxC4G...","Content-Type": "application/json"
          },body: JSON.stringify({
              to:"e56_nKx5Ejm1HyWHKcvZFq:APA91bH-...-nKE9YEILYu7RQBBiyCs_CUo2IC0DX-87cMgmMcYwvYQ1yg0BmqWfAgbbkfPtfzXGGOdzmvxVX2wBlwhnnK5oUxjtXalQ4T5CM7IQOhertbXc",notification : {
                "title": "Message recieived from:","body": message,"click_action": "http://localhost:3000/","icon": "http://url-to-an-icon/icon.png"
              },})
        }
        
        fetch("https://fcm.googleapis.com/fcm/send",fetchOptions)
          .then(response =>console.log(response))
          .then(data => console.log(data));
}

还为 index.js 文件

中使用的 serviceWorker.js 文件添加代码
// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production,and gives
// it offline capabilities. However,it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page,after all the
// existing tabs open on the page have been closed,since prevIoUsly cached
// resources are updated in the background.



const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL,window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load',() => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl,config);

        // Add some additional logging to localhost,pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more,'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl,config);
      }
    });
  }
}

function registerValidSW(swUrl,config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point,the updated precached content has been fetched,// but the prevIoUs service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
                'New content is available and will be used when all ' +
                  'tabs for this page are closed.'
              );

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point,everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:',error);
    });
}

function checkValidServiceWorker(swUrl,config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists,and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl,config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

我正在端口3000上运行该应用程序,我可以看到google chrome会抛出如下错误

服务人员注册失败。我不知道我做错了什么。

enter image description here

enter image description here

请您帮我解决问题?另外,请告诉我您是否还有其他要求。

解决方法

1。您应该在firebase-messaging-sw.js中使用onBackgroundMessage而不是setBackgroundMessageHandler

2.put

        export const initializeFirebase = () => {
firebase.initializeApp({

    apiKey: "***",authDomain: "***",databaseURL: "***",projectId: "***",storageBucket: "***",messagingSenderId: "***",appId: "***",measurementId: "G-***"
});
const messaging = firebase.messaging();}

export const askForPermissioToReceiveNotifications = async (registration) => {
try {

    const messaging = firebase.messaging();
    await messaging.onMessage(notification => {
        console.log('Notification received!',notification);
        message.info(notification?.data?.title + ':' + notification?.data?.body)
    });

    const registration = await navigator.serviceWorker
        .register('firebase-message-sw.js',{scope: "/",updateViaCache: 'none'})
        .then((registration) => {
            return registration;
        }).catch(e => {
        });
    await Notification.requestPermission().then((callBack) => {
        console.log(callBack)
    }).catch(e => {
    });
    const token = await messaging.getToken({
        vapidKey: 'BML-',serviceWorkerRegistration: registration
    });
    await //send token


    console.log('token do usuário:',token);
    return token;

} catch (error) {
    console.error(error);
}}

在您的firebase.js文件中

3。在serviceworker.register()之前调用index.js中的initializeFirebase()和askForPermissioToReceiveNotifications();

对我来说很好...