firebase - 如何在 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));
}
解决方案
推荐阅读
- java - 用货币代码解析(本地化)价格的正确方法?
- r - 聚合数据时的行数返回率
- c# - 如何从 GLControl 的底部和顶部剪切/隐藏投影区域 - openTK
- php - 推送通知在 WooCommerce 优惠券中如何工作?
- preact - 需要时突出显示带有红色边框的输入类型
- java - 在 BST 中插入元素时获取 NullPointerException
- symfony - 带有 URL 参数和注入服务的 Symfony 控制器
- android - 如何根据他们的数量,水平和垂直地制作recyclerview布局视图?
- node.js - 如何在 nodejs express 应用程序中使用nested-subfloders 路由?
- python - 试图制作一个检查字符串的算法,然后输出最长的子字符串