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上关注我。

翻译自: https://www.freecodecamp.org/news/how-to-add-push-notifications-to-a-web-app-with-firebase-528a702e13e1/

firebase 推送

firebase 推送_如何使用Firebase向Web应用程序添加推送通知?相关推荐

  1. js轮询导致服务器瘫痪_演进:Tengine 从 Web 代理服务器 到 分布式推送服务器

    Tengine Tengine 作为代理服务器,在集团有着广泛的应用基础,从 部署在 应用单机上的 Tengine ,到作为集群式部署的统一接入 Aserver ,可以说集团几乎所有应用机器均运行着 ...

  2. firebase登录验证_如何使用Firebase通过三步向身份验证本机添加身份验证

    firebase登录验证 Authentication allows us to secure our apps, or limit access for non-user members. Auth ...

  3. nodejs android 推送,利用Nodejs怎么实现一个微信小程序消息推送功能

    利用Nodejs怎么实现一个微信小程序消息推送功能 发布时间:2021-01-20 13:55:29 来源:亿速云 阅读:92 作者:Leah 今天就跟大家聊聊有关利用Nodejs怎么实现一个微信小程 ...

  4. win10推送_微软 Win10 最稳版本 2004 正式版推送!最低配置要求汇总,全新 UI 虚拟桌面,支持几乎所有 CPU...

    5月28日消息 ,微软开始推送2020 Windows 10更新五月版(2004版本)系统更新,现在包括微软Windows 10官网工具.MSDN订阅网站都已经发布了Windows 10版本2004的 ...

  5. java 实现微博推送_编写调用新浪微博API的Java程序来发送微博

    首先,需要下载新浪微博的sdk,这里附上地址:http://vdisk.weibo.com/s/z7ifc2gccwc1b 下载完了之后解压,然后打开myeclipse,新建项目,再把刚才解压出来的i ...

  6. java邮箱设置密送_修改后可以发送附件、抄送、密送的javabean,吐血推荐~(javamail范例)...

    修改后可以发送附件.抄送.密送的javabean,吐血推荐~(javamail范例) 作者:Andy.m    文章来源:www.jspcn.net 发布日期:2004年02月16日 /* *Auth ...

  7. java代码输出伞_在伞中集成测试Web应用程序的问题

    我正在研究凤凰应用程序 . 此应用程序是伞形应用程序的一部分 . 在这个保护伞中,我有一些小应用程序负责应用程序的不同区域,它们是: phoenix web api("api") ...

  8. maven 常量字符串过长_从基于Maven的Web应用程序获取版本字符串

    maven 常量字符串过长 打包maven项目时,它将自动在其中生成pom.properties文件,其中将包含版本,artifactId和groupId信息. 这些在运行时很方便拥有并显示给您的We ...

  9. wordpress 插件_如何为您的Web应用程序创建WordPress插件

    wordpress 插件 by Feedier by Alkalab 由Feedier通过Alkalab 如何为您的Web应用程序创建WordPress插件 (How to create a Word ...

最新文章

  1. RT-Thread优化智能车设计
  2. virtualbox 安装ubuntu 时,看不到继续、退出按钮?共享文件无权限?
  3. 粒子群PSO优化算法学习笔记 及其python实现(附讲解如何使用python语言sko.PSO工具包)
  4. 用vbs自动切换不同网段的IP
  5. java dateTime + long
  6. junit:junit_简而言之,JUnit:测试结构
  7. 2019年3月计算机考试操作,2019年3月计算机二级C++操作练习题(一)
  8. Redis源代码分析(十)--- testhelp.h小测试框架和redis-check-aof.c 日志检测
  9. Cure Your Acne by NOT Eating This!
  10. java fx choicebox_JavaFX使用ChoiceBox、ComboBox实现下拉列表
  11. jpress-项目升级
  12. Java的时间格式化
  13. 小程序上线后部分图片不显示的问题
  14. word,excel重难点问题解答
  15. 从京东双11战报中,找到未来值得国产品牌看好的发展机遇
  16. 四轮转向系统横摆角速度控制simulink仿真模型,利用滑模控制算法,基于八自由度车辆模型
  17. 利用“顺丰速运”下发GuLoader恶意软件的风险分析
  18. 掘地三尺搞定 Redis 与 MySQL 数据一致性问题
  19. 计算机网络,ping连接同一个WiFi的电脑,回复无法访问目标主机,但是数据包已接收(防火墙已关)
  20. 使用NVM安装NodeJS并解决npm下载依赖失效问题(最全流程)

热门文章

  1. 系统分析与设计 实验一用例模型
  2. String.hashCode 哈希值出现重复?
  3. Spring框架之(无参、有参)构造方法与setter方法的初始化
  4. MySQL之模糊查询
  5. mysql 中文截取_mysql 截取中文字符
  6. VUE input唤起键盘 底部固定的标签被顶上去解决办法
  7. 小程序画布,随机24个数显示在画布上面,不可重叠
  8. 微信小程序学习做动画效果
  9. yii1框架,事务使用方法
  10. 数据库索引-基本知识