firebase 推送_如何使用Firebase向Web应用程序添加推送通知?
firebase 推送
by Leonardo Cardoso
由莱昂纳多·卡多佐(Leonardo Cardoso)
如何使用Firebase向Web应用程序添加推送通知? (How to add push notifications to a web app with Firebase ?+?)
As web applications evolve, it is increasingly common to come across functionality that you’d normally associate with a native app in a web app. Many sites send notifications to their users through the browser for various events that occur within the web app.
随着Web应用程序的发展,遇到通常与Web应用程序中的本机应用程序关联的功能变得越来越普遍。 许多网站都会通过浏览器向用户发送有关Web应用程序中发生的各种事件的通知。
Today, I’ll show you the steps required, in detail, to achieve such functionality in your web app using Firebase.
今天,我将向您详细介绍使用Firebase在Web应用程序中实现此类功能所需的步骤。
Firebase通知 (Notifications with Firebase)
Firebase is a platform that offers various services for mobile and web applications and helps developers build apps quickly with a lot of features.
Firebase是一个平台,可为移动和Web应用程序提供各种服务,并帮助开发人员使用许多功能快速构建应用程序。
To send the notifications, we will use the service called Cloud Messaging, which allows us to send messages to any device using HTTP requests.
要发送通知,我们将使用称为Cloud Messaging的服务,该服务使我们可以使用HTTP请求将消息发送到任何设备。
项目设置 (Project Setup)
First of all, you need to have a Firebase account and you’ll need to create a new project within it.
首先,您需要拥有一个Firebase帐户,并且需要在其中创建一个新项目。
For this demo setup, I will use a simple project created with the create-react-app, but you can use the same code anywhere else that uses JavaScript.
对于此演示设置,我将使用一个由create-react-app创建的简单项目,但是您可以在使用JavaScript的其他任何地方使用相同的代码。
In addition to that, we need to add the Firebase library to the project.
除此之外,我们需要将Firebase库添加到项目中。
npm install firebase --save
因此,让我们开始编码吧! (So let’s get coding!)
Now that we’ve done our setup, we can begin coding the module that will be in charge of notifications.
现在,我们已经完成了设置,我们可以开始对负责通知的模块进行编码了。
Let’s create a file inside the project directory called push-notification.js.
让我们在项目目录中创建一个名为push-notification.js 。
Inside the file, let’s create a function that initializes Firebase and passes the keys of your project.
在文件内部,我们创建一个函数来初始化Firebase并传递项目的键。
import firebase from 'firebase';
export const initializeFirebase = () => {
firebase.initializeApp({
messagingSenderId: "your messagingSenderId"
});
}
Well, now that we have the function we need to call it.
好了,现在我们有了需要调用的函数。
Inside the entry point of your project, import the function and call it.
在项目的入口点内,导入函数并调用它。
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { initializeFirebase } from './push-notification';
ReactDOM.render(<App />, document.getElementById('root'));
initializeFirebase();
You can find the keys to your project inside the Firebase Console.
您可以在Firebase控制台中找到项目的键。
服务人员 (Service Workers)
A service worker is a script that your browser runs in the background, separate from the web page, enabling features that do not require a web page or user interaction.
服务工作者是一个脚本,您的浏览器在后台运行,与网页分开,从而启用不需要网页或用户交互的功能。
To receive the onMessage event, your app needs a service worker. By default, when you start Firebase, it looks for a file called firebase-messaging-sw.js.
要接收onMessage事件,您的应用程序需要服务人员。 默认情况下,启动Firebase时,它将查找名为firebase-messaging-sw.js的文件。
But if you already have one and want to take advantage of it to receive notifications, you can specify during the Firebase startup which service worker it will use. For example:
但是,如果您已经拥有一个服务并希望利用它来接收通知,则可以在Firebase启动期间指定它将使用哪个服务工作者。 例如:
export const inicializarFirebase = () => {
firebase.initializeApp({
messagingSenderId: 'your messagingSenderId'
});
navigator.serviceWorker
.register('/my-sw.js')
.then((registration) => {
firebase.messaging().useServiceWorker(registration);
});
}
This service worker will basically import the script needed to show the notifications when your app is in the background.
当您的应用程序在后台运行时,该服务人员将基本上导入显示通知所需的脚本。
We need to add firebase-messaging-sw.js to the location where your files are served. As I’m using the create-react-app, I’m going to add it inside the public folder with the following content:
我们需要将firebase-messaging-sw.js添加到提供文件的位置。 当我使用create-react-app时,我将其添加到公共文件夹中,内容如下:
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "your messagingSenderId again"
});
const messaging = firebase.messaging();
要求发送通知的权限 (Requesting permission to send notifications)
Well, everyone knows how annoying it is to enter the site and ask for authorization to send notifications. So let’s do it another way!Let the user choose whether or not to receive notifications.
好吧,每个人都知道进入该网站并要求授权发送通知是多么烦人。 因此,让我们以另一种方式做吧!让用户选择是否接收通知。
First of all, let’s create the function that will make the request and return the user’s token.
首先,让我们创建一个函数,该函数将发出请求并返回用户的令牌。
Inside our push-notification.js file, add the function:
在我们的push-notification.js文件中,添加函数:
export const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('token do usuário:', token);
return token;
} catch (error) {
console.error(error);
}
}
We need to call this function from somewhere, so I’ll add it at the click of a button.
我们需要从某个地方调用此函数,因此我将在单击按钮时将其添加。
import React from 'react';
import { askForPermissioToReceiveNotifications } from './push-notification';
const NotificationButton = () => (
<button onClick={askForPermissioToReceiveNotifications} >
Clique aqui para receber notificações
</button>
);
export default NotificationButton;
Okay, let’s see it working:
好吧,让我们看看它的工作原理:
发送通知 (Sending notifications)
To send the notification, we need to make a request to the Firebase API informing it of the token the user will receive.
要发送通知,我们需要向Firebase API发出请求,以通知用户用户将收到的令牌。
In the examples below I use Postman, but you can do this from any other REST client.
在下面的示例中,我使用Postman,但是您可以从任何其他REST客户端执行此操作。
Basically, we need to make a POST request to https://fcm.googleapis.com/fcm/send by sending a JSON in the request body.
基本上,我们需要通过在请求正文中发送JSON向https://fcm.googleapis.com/fcm/send发出POST请求。
Below is the structure of the JSON that will be sent:
以下是将发送的JSON的结构:
{
"notification": {
"title": "Firebase",
"body": "Firebase is awesome",
"click_action": "http://localhost:3000/",
"icon": "http://url-to-an-icon/icon.png"
},
"to": "USER TOKEN"
}
In the request header, we need to pass the server key of our project in Firebase and the content-type:
在请求标头中,我们需要在Firebase中传递项目的服务器密钥和content-type:
Content-Type: application/json
Authorization: key=SERVER_KEY
The server key is found in the project settings in the Firebase Console under the Cloud Messaging tab.
服务器密钥可在Firebase控制台的“云消息”选项卡下的项目设置中找到。
行动通知 (Notifications in action)
Remember that notifications will only appear when your app is minimized or in the background.
请记住,只有在您的应用程序最小化或在后台运行时,通知才会显示。
That is how we send a direct notification to a device.
这就是我们向设备发送直接通知的方式。
向一组用户发送通知 (Send notifications to a group of users)
Well, now that we’ve seen how to send a notification to one user, how do we send a notification to multiple users at once?
好了,既然我们已经了解了如何向一个用户发送通知,那么我们如何一次向多个用户发送通知?
To do this, Firebase has a feature called topic, where you insert multiple tokens for a specific topic, and you can send the same notification to all of them from a single request.
为此,Firebase具有一个名为topic的功能,您可以在其中为特定主题插入多个令牌,并且可以从单个请求向所有令牌发送相同的通知。
这该怎么做 (How to do this)
We will basically send a POST request to the address https://iid.googleapis.com/iid/v1/TOKEN/rel/topics/TOPIC_NAME, passing the topic name and the token in the URL.
我们基本上将POST请求发送到地址https://iid.googleapis.com/iid/v1/ TOKEN / rel / topics / TOPIC_NAME , 在URL中传递主题名称和令牌。
Do not forget to pass in the header the same authorization that we used to send the notification.
不要忘记在标头中传递与我们用来发送通知相同的授权。
Sending the notification to users subscribed to any topic is very similar to sending a notification to a single user. The difference is that we need to pass the topic name in the “to” attribute instead of the token.
向订阅了任何主题的用户发送通知与向单个用户发送通知非常相似。 区别在于我们需要在“ to”属性中传递主题名称,而不是令牌。
See the example below:
请参阅以下示例:
{
"notification": {
"title": "Firebase",
"body": "Firebase topic message",
"click_action": "http://localhost:3000/",
"icon": "http://localhost:3000/icon.png"
},
"to": "/topics/TOPIC_NAME"
}
结论 (Conclusion)
Thanks for reading this! I hope you now understand how to make use of push notifications. The repository with the demo code can be found here.
感谢您阅读本文! 希望您现在了解如何使用推送通知。 可以在此处找到带有演示代码的存储库。
To get notified of my future posts, follow me on GitHub or Twitter.
要通知我将来的帖子,请在GitHub或Twitter上关注我。
firebase 推送
更多推荐

所有评论(0)