首页 > 解决方案 > 如何在 Next JS 中显示 Firebase 云通知?

问题描述

我的 Next Js 应用程序在我的浏览器中收到来自 Firebase Cloud Notifications 的推送通知。

我无法弄清楚如何在前台显示通知并将它们显示为我的登录页面中的弹出窗口。

我的服务人员和 firebase-messaging 使用下面的代码可以正常工作。

任何帮助表示赞赏。

提前致谢。

我的 Firebase.js

import "firebase/messaging";
import firebase from "firebase/app";
import localforage from "localforage";
const firebaseCloudMessaging = {
//checking whether token is available in indexed DB
  tokenInlocalforage: async () => {
    return localforage.getItem("fcm_token");
  },
init: async function () {
if (!firebase.apps.length) {
  firebase.initializeApp({
apiKey: "AIzaSyDfbg6HxWSJdqLADarDcUyEF8hLWMu3kYw",
    authDomain: ",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
  });
 try {
    const messaging = firebase.messaging();
    const tokenInLocalForage = await this.tokenInlocalforage();
    //if FCM token is already there just return the token
    if (tokenInLocalForage !== null) {
      console.log("printing tokenInLocalForage", tokenInLocalForage);
      return tokenInLocalForage;
    }
 //requesting notification permission from browser
    const status = await Notification.requestPermission();
    console.log(status, "printing status");
    if (status && status === "granted") {
      console.log(status, "printing status1");
      //getting token from FCM
      const fcm_token = await messaging.getToken({
        vapidKey:
          "BKrO1YU0yZTLNla_yrI2H9yRHtXG9TEpfzkbOxDS4dR4WAAwNPCuLc1GRQDFxIPs86DUnORT00hn4b5FO0PoxCg",
      });
      if (fcm_token) {
        console.log(fcm_token, "this is the fcm token");
        //setting FCM token in indexed db using localforage
        localforage.setItem("fcm_token", fcm_token);
        console.log("fcm token", fcm_token);
        //return the FCM token after saving it
        return fcm_token;
      }
    }
  } catch (error) {
    console.error(error);
    return null;
  }
 }
},
},

我的 firebase-messaging.js

importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js");
if (!firebase.apps.length) {
 firebase.initializeApp({
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
  });
firebase
.messaging()
.getToken({
 vapidKey: ""
 })
.then((currentToken) => {
  console.log(currentToken);
})
.catch(function (err) {
  // handle error
});


firebase
    .messaging()
    .setBackgroundMessageHandler((payload) => console.log("payload", payload));
}

标签: firebasenext.jsfirebase-cloud-messaging

解决方案


推荐阅读