我们将在React上创建一个MVP应用程序,它将通过使用Firebase云消息接收推送通知(即使是在后台模式或应用程序关闭时)。这是一件容易的事情,但也有一些时刻值得关注。您可以在项目的Firebase设置中找到下面描述的所有必需的密钥/令牌。 添加manifest.json 添加一个清单。json文件到已经有一个index.html文件和gcm_sender_id的文件夹。如果您已经有了宣言,只需添加这一行。按原样插入下面的值,不做任何更改。
{
"gcm_sender_id": "103953800507"
}
连接index.html文件中的声明;您的href可能不同。
<head>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
</head>
为了确保一切正常工作,我们需要打开浏览器的dev tools面板并导航到Network选项卡,请确保清单。json是由您的应用程序加载的,它包含gcm_sender_id。
设置用于接收消息的服务工作者 创建一个公共/firebase- messages -sw.js文件。这是一个未来的服务工作者,它将以后台模式接收消息。setBackgroundMessageHandler负责这一点。在下面这段代码中,您可以通过单击工具提示消息addEventListener('notificationclick…如果选项卡未激活或关闭。
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({
// Project Settings => Add Firebase to your web app
messagingSenderId: "1062407524656"
});
const messaging = firebase.messaging();
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
// ...
});
为了让工人开始工作,您必须从一开始就注册它。我是在应用程序进入点之前做的。官方文档建议您以稍微不同的方式注册FCM worker,但是,根据Webpack设置,您可能会在上载该worker时得到一个不正确的mime类型错误。在我看来,下面是最可靠的方法。
import ReactDOM from "react-dom";
import App from "./App";
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration.scope);
})
.catch(function(err) {
console.log("Service worker registration failed, error:", err);
});
}
ReactDOM.render(, document.getElementById("root"));
确保加载的worker没有错误。
浏览器注册了它。
检查浏览器控制台是否有任何声明或服务工作人员错误,并修复它们(如果有的话)。 设置Firebase SDK
yarn add firebase
# or
npm install firebase
连接Firebase云消息传递 创建一个src/init-fcm.js文件,在其中初始化FCM。在下面的评论中,您可以看到从哪里获得密钥。
import * as firebase from "firebase/app";
import "firebase/messaging";
const initializedFirebaseApp = firebase.initializeApp({
// Project Settings => Add Firebase to your web app
messagingSenderId: "106240...4524656"
});
const messaging = initializedFirebaseApp.messaging();
messaging.usePublicVapidKey(
// Project Settings => Cloud Messaging => Web Push certificates
"BD6n7ebJqtOxaBS8M7xtBwSxgeZwX1gdS...6HkTM-cpLm8007IAzz...QoIajea2WnP8rP-ytiqlsj4AcNNeQcbes"
);
export { messaging };
现在将您所做的一切连接到React组件。这里最重要的操作发生在生命周期方法componentDidMount中。记住这是一个MVP,在一个真实的项目中,你可以把所有东西分配到不同的地方。
// ...
import { messaging } from "./init-fcm";
// ...
async componentDidMount() {
messaging.requestPermission()
.then(async function() {
const token = await messaging.getToken();
})
.catch(function(err) {
console.log("Unable to get permission to notify.", err);
});
navigator.serviceWorker.addEventListener("message", (message) => console.log(message));
}
为了让服务开始向我们发送消息,我们应该让它知道我们的应用程序的地址。为此,我们需要获得一个令牌并将其传递给服务器。在这个令牌的帮助下,服务器将知道我们注册的地址。 为了获得令牌,我们必须允许浏览器接收推送消息。在这种情况下,消息传递..requestPermission()将在加载页面上显示以下内容:
您可以随时更改此配置:
只有在上面描述的权限之后,message . gettoken()才能获得令牌。 为了接收消息,我们必须在onMessage上安装处理程序。正式文件建议了下列方法:
messaging.onMessage((payload) => console.log('Message received. ', payload));
这种方法只有在应用程序所在的选项卡处于焦点位置时才有效。我们将把处理程序放在服务工作程序中的客户机上。根据选项卡焦点的不同,消息将具有不同的结构。 如果您现在有点困惑,请查看设置一个JavaScript Firebase云消息客户端应用程序-官方文档与一步一步的指南。它很好地描述了令牌更新的逻辑。不过,我们将跳过它,这样文章就不会太长。 发送和接收消息 我们将用邮递员来做这件事。 1. 设置查询标题。表单key=中的授权标题。发送方(服务器)的键是在项目设置中设置“云消息”“服务器键”。
2. 设置查询主体
在“to:”字段中,使用之前从message . gettoken()获得的令牌。对于数据传输,我们将使用“data”字段,它可以有任何嵌套。此外,请查看关于编写查询结构的官方文档。有几种查询类型,浏览器以不同的方式处理它们。在我看来,“data”查询是最普遍的查询。然后单击Send按钮,在浏览器中接收之前发送的信息。 您可以用JavaScript使用控制台做的所有事情定制发送个性化推送通知阿里云服务器2折起 新用户限购四台织梦如何安装搭建手机端站点网站安全服务平台备案流程一阿里云商标注册服务,可担保退款navigator.serviceWorker.addEventListener("message", (message) => console.log(message)); |