使用 Firebase(云消息传递)进行 PWA 推送通知 - 第 1 部分
您的 PWA 中的推送通知
您是否想过如何将著名/烦人的推送通知添加到您的应用?好吧,在本教程中,我将向您展示如何使用Firebase Cloud Messaging来实现。
注意:本教程需要一些关于 PWAs 和服务工作者的基本知识。
您可以在这里查看我对 PWA 和 Service Worker 的介绍
以及有关 PWA 和通知的信息。
在开始之前,我需要澄清一下,通知 API 和推送 API 并不相同。人们经常把它们混淆。
Push API: Push API 使 Web 应用能够接收服务器推送的消息,无论该 Web 应用是在前台运行还是当前已加载到用户代理上。这使得开发者能够向选择接收消息的用户发送异步通知和更新,从而更好地与用户及时互动,获取最新内容。
我们开始做吧!!
最终代码位于 repo 内的 FINAL 分支中。
如您所见,我已经为您创建了应用程序的基本结构,因为我们只需要担心如何使用 Firebsae 云消息服务通过推送通知发送消息。
- 导航到 index.html 文件。注意,我已经为你导入了 Firebase:
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-messaging.js"></script>
```javascript
1. Navigate to Firebase.com and create an account if you don't have one.
2. Once you are in the Firebase console, navigate to **project settings** (in case you don't have a project yet - just create it there)

1. Inside of project setting, under the **General tab** scroll all the way down to find your **Firebase SDK snippet** (if it's not there yet - this means that you've created a new project and need to add an app there. Either way, this can be done at the same place where you will have your SDK snippet - under the **General tab** ). Copy/paste it in a safe place. The snippet should look like this:

1. Go to your **index.js** file and copy/paste the following after the global variables that I have declared for you. Replace it with your project's customized code - the snippet from step 4.
```javascript
const config = {
apiKey: "XXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXXXX"
};
```javascript
1. Right after - initialize the firebase instance.
```javascript
firebase.initializeApp(config);
- 然后,我们将创建一个名为的常量
messaging
并将其设置为 firebase 消息服务。
const messaging = firebase.messaging();
- 是时候向 Firebase 云消息传递请求权限了。一旦我们获得批准,他们就会给我们一个 token 作为承诺。
messaging
.requestPermission()
.then(() => {
message.innerHTML = "Notifications allowed";
return messaging.getToken();
})
.then(token => {
tokenString.innerHTML = "Token Is : " + token;
})
.catch(err => {
errorMessage.innerHTML = errorMessage.innerHTML + "; " + err;
console.log("No permission to send push", err);
});
- 然后,我们将使用该
messaging.onMessage()
方法。该方法用于接收当前正在查看页面(页面位于前台)的所有用户的数据和通知负载。
为此,我们添加以下代码:
messaging.onMessage(payload => {
console.log("Message received. ", payload);
const { title, ...options } = payload.notification;
});
- 注意firebase-messaging-sw.js文件。Firebase SDK 会搜索此文件名。该文件必须位于项目的根目录下。Firebase SDK 会在后台执行一些操作,将该文件注册为 Service Worker。
- 在firebase-messaging-sw.js中,通过传入 messagesSenderId 来初始化 Firebase 应用。发件人 ID 可以在项目设置中找到,如下图所示。
firebase.initializeApp({
messagingSenderId: "XXXXXXX"
});
- 检索 Firebase Messaging 的实例,以便它可以处理后台消息。
const messaging = firebase.messaging();
```javascript
1. Background message handler (this one will be invoked when the page is in the background)
```javascript
messaging.setBackgroundMessageHandler(payload => {
const notification = JSON.parse(payload.data.notification);
const notificationTitle = notification.title;
const notificationOptions = {
body: notification.body
};
//Show the notification :)
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
测试通知
- 使用任何http 服务器运行应用程序
- 在您的云消息传递设置(选项卡中
Firebase Console > Project Settings
)中复制服务器密钥。
- 如果您有Postman http 客户端,请执行以下操作:
发布网址:* https://fcm.googleapis.com/fcm/send *
标题:
内容类型-application/json
授权-key=server_key
身体:
{
"notification": {
"title": "Testing Notification!",
"body": "Firebase is awesome",
"click_action": "http://127.0.0.1:5501/index.html",
"icon": "http://the-link-to-image/icon.png"
},
"to": "YOUR TOKEN GOES HERE"
}
然后,点击发送按钮。此时,如果我们的应用处于前台(当前浏览器标签页已打开),那么您将在控制台中看到我们发送的消息 - 由 处理messaging.onMessage
。
但如果它在后台,它将由messaging.setBackgroundMessageHandler
服务工作者处理,你会看到类似这样的内容:
通过部署到 Firebase 或其他托管服务提供商,在真机上测试您的应用。如果您想在 Firebase 上托管您的应用,请查看我的其他教程。
在接下来的教程中,我将向您展示如何成功订阅通知并使用 Firebase 控制台推送通知。
This Dot Inc. 是一家咨询公司,包含两个部门:媒体部门和实验室部门。This Dot Media 负责让开发人员及时了解 Web 平台的最新进展。This Dot Labs 通过指导和培训等方式为团队提供 Web 平台专业知识。
鏂囩珷鏉ユ簮锛�https://dev.to/thisdotmedia/pwa-push-notifications-with-firebase-cloud-messaging-pt1-10ak