当前位置: 首页 > 编程日记 > 正文

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

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

firebase 推送

相关文章:

lucene构建同义词分词器

lucene4.0版本号以后 已经用TokenStreamComponents 代替了TokenStream流。里面包含了filter和tokenizer 在较复杂的lucene搜索业务场景下&#xff0c;直接网上下载一个作为项目的分词器&#xff0c;是不够的。那么怎么去评定一个中文分词器的好与差&#xff1a;一般来讲。有两个…

正则匹配出字符串中两串固定字符区间的所有字符

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 效果&#xff1a;匹配两个字符串区间的字符串 代码&#xff1a; var dd[];var str is_img"https://www.baidu.com/"is_img11is_img"https://www.baidu.com/"is…

识别手写字体app_我如何构建手写识别器并将其运送到App Store

识别手写字体app从构建卷积神经网络到将OCR部署到iOS (From constructing a Convolutional Neural Network to deploying an OCR to iOS) 项目动机✍️?? (The Motivation for the Project ✍️ ??) While I was learning how to create deep learning models for the MNIS…

20155307 2016-2017-2 《Java程序设计》第10周学习总结

20155307 2016-2017-2 《Java程序设计》第10周学习总结 教材学习内容总结 网络编程&#xff1a;就是在两个或两个以上的设备(例如计算机)之间传输数据。程序员所作的事情就是把数据发送到指定的位置&#xff0c;或者接收到指定的数据。在发送和接收数据时&#xff0c;大部分的程…

WinForm 实现验证码

private void CheckIdentifyingCode() { Random r new Random(); string str ""; for (int i 0; i < 5; i) { int a r.Next(0, 10); str a;//将数字连接到一块 } Bitmap bm new Bitmap(150, 90);//创建位图对象 Graphics g Graphics.FromImage(bm);//在bm中…

微信小程序打开预览下载的文件

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 使用 wx.openDocument(obj) 方法预览 wx.downloadFile({url: http://example.com/somefile.pdf,success: function (res) {var filePath res.tempFilePathwx.openDocument({filePath: filePath,success…

aws lambda_为什么我会自动删除所有旧的推文以及我用来执行此操作的AWS Lambda函数...

aws lambdaFrom now on, my tweets are ephemeral. Here’s why I’m deleting all my old tweets, and the AWS Lambda function I’m using to do all this for free.从现在开始&#xff0c;我的推文只是短暂的。 这就是为什么我删除所有旧的推文&#xff0c;以及免费使用所有…

Topcoder SRM 657DIV2

前言: 像我这样一直在DIV2的弱菜。。不知道说什么了。 A:一定判断有8个‘R’&#xff0c;每行 每列只有一个 B题&#xff1a;大概是 int E,int EM,int M,int MH,int H 然后EM可以给值到E&#xff0c;M&#xff0c;MH可以给值到H&#xff0c;M&#xff1b; 我的做法二分&#x…

微信小程序换行,空格的写法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 1.文本超出部分自动换行&#xff0c;前后对比 实现代码&#xff1a; flex-wrap: warp;white-space: pre-wrap; 2.text 手动添加换行的写法 { text: 12测试换\n行符&#xff0c;测试\…

我是如何在尼日利亚的沃里创立Google Developers Group GDG分会的,并达到了100位成员...

It only takes a spark to get a fire going, and soon all those around can warm up in its glowing. — Kurt Kaiser, Pass It On只需要一点火花就能使火熄灭&#xff0c;周围的所有人很快就会在炽热的火焰中升温。 — Kurt Kaiser&#xff0c;传递下去 I am convinced beyo…

ES6 你可能不知道的事 – 基础篇

ES6 你可能不知道的事 – 基础篇 转载作者&#xff1a;淘宝前端团队&#xff08;FED&#xff09;- 化辰 链接&#xff1a;taobaofed.org/blog/2016/07/22/es6-basics/ 序 ES6&#xff0c;或许应该叫 ES2015&#xff08;2015 年 6 月正式发布&#xff09;&#xff0c;对于大多数…

Android线程之主线程向子线程发送消息

和大家一起探讨Android线程已经有些日子了&#xff0c;谈的最多的就是如何把子线程中的数据发送给主线程进行处理&#xff0c;进行UI界面的更新&#xff0c;为什么要这样&#xff0c;请查阅之前的随笔。本篇我们就来讨论一下关于主线程向子线程如何发送数据&#xff0c;这个用的…

HTML上传excel文件,php解析逐条打印输出

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; phpExcel文件下载 ←跳转地址 demo <!DOCTYPE html> <html lang"zh"><head><meta charset"UTF-8"><title>Title</title>…

javascript编写_如何通过编写自己的Web开发框架来提高JavaScript技能

javascript编写Have you ever asked yourself how a framework works?您是否曾经问过自己框架是如何工作的&#xff1f; When I discovered AngularJS after learning jQuery many years ago, AngularJS seemed like dark magic to me.多年前学习jQuery后&#xff0c;当我发现…

2016ACM/ICPC亚洲区大连站现场赛题解报告(转)

http://blog.csdn.net/queuelovestack/article/details/53055418 下午重现了一下大连赛区的比赛,感觉有点神奇,重现时居然改了现场赛的数据范围,原本过的人数比较多的题结果重现过的变少了,而原本现场赛全场过的人最少的题重现做出的人反而多了一堆,不过还是不影响最水的6题,然…

微信小程序插件新增能力

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; “ 小程序插件能力升级&#xff1a;开放插件登录能力&#xff0c;帮助插件开发者更好地管理用户&#xff1b;支持在插件内使用微信支付能力&#xff0c;便于用户在插件内完成预订、购…

ubutun:从共享文件夹拷贝文件尽量使用cp命令而不是CTRL+C/V

为了方便&#xff0c;VBOX安装的Ubuntu&#xff0c;并在硬盘上创建了一个与Windows的共享文件夹sharefolder方便在两个系统之间传文件 但是经常发现的问题就是从sharefolder中拷贝文件到ubuntu中会出现很多毛病&#xff0c;比如说经常按了CTRLC之后没有拷贝最新的文件&#xff…

影像锐化工具_如何以及为什么要进行工具改造:花在锐化斧头上的时间永远不会浪费...

影像锐化工具by Harshdeep S Jawanda通过Harshdeep S Jawanda 如何以及为什么要进行工具改造&#xff1a;花在锐化斧头上的时间永远不会浪费 (How and why you should tool-up: time spent sharpening your axe is never wasted) There is this old anecdote about two friend…

ListT随机返回一个

/// <summary> /// 随机返回一条数据 /// </summary> /// <param name"list"></param> /// <returns></returns> protected string GetRandomData(List<string> list) {return list.OrderBy(_ > Guid.NewGuid()).First…

微信小程序插件功能页开发详细流程

有问题可以扫码加我微信&#xff0c;有偿解决问题。承接小程序开发。 微信小程序开发交流qq群 173683895 、 526474645 &#xff1b; 正文&#xff1a; 关于新出的微信小程序插件功能页做一下记录&#xff0c;希望能帮到大家 步骤&#xff1a; 1.打开开发者工具&#x…

(拆点+最小路径覆盖) bzoj 2150

2150: 部落战争 Time Limit: 10 Sec Memory Limit: 259 MBSubmit: 518 Solved: 298[Submit][Status][Discuss]Description lanzerb的部落在A国的上部&#xff0c;他们不满天寒地冻的环境&#xff0c;于是准备向A国的下部征战来获得更大的领土。 A国是一个M*N的矩阵&#xff0…

使用Flow检查React,Redux和React-Redux的全面指南

by Fabian Terh由Fabian Terh 使用Flow检查React&#xff0c;Redux和React-Redux的全面指南 (A comprehensive guide to type checking React, Redux, and React-Redux with Flow) This article is divided into 4 sections:本文分为4个部分&#xff1a; Type checking Redux…

微信小程序WebSocket实现聊天对话功能完整源码

相关文章&#xff1a; 1.小程序聊天群&#xff0c;发送语音&#xff0c;文字&#xff0c;图片。 2.微信小程序集成腾讯IM&#xff0c;实现实时音视频通话&#xff0c;1V1聊天 3.云开发微信小程序聊天群 4.接入网易云信IM即时通讯的微信小程序聊天室 5.微信小程序聊天功能 …

codevs 1203 判断浮点数是否相等

1203 判断浮点数是否相等 时间限制: 1 s空间限制: 128000 KB题目等级 : 青铜 Bronze题目描述 Description给出两个浮点数&#xff0c;请你判断这两个浮点数是否相等输入描述 Input Description输入仅一行&#xff0c;包含两个浮点数输出描述 Output Description输出仅一行&…

通过代码自定义cell(cell的高度不一致)

我们知道&#xff0c;在iOS中&#xff0c;自定义cell的方式有两种&#xff1a; 一是通过xib创建 .二是通过代码自定义cell 这里我说下通过代码自定义的cell。 当我们的应用显示的cell比较复杂&#xff0c;显示的行高都不一样&#xff0c;比如新浪微博 这时用系统自带的cell…

通过构建城市来解释HTML,CSS和JavaScript之间的关系

by Kevin Kononenko凯文科诺年科(Kevin Kononenko) 通过构建城市来解释HTML&#xff0c;CSS和JavaScript之间的关系 (The relationship between HTML, CSS and JavaScript explained by building a city) If you have ever visited a walkable city like New York, then you c…

url参数解析 url解析 ?解析成对象

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 代码&#xff1a; // url参数解析 function getUrlkey(url) {var params {};var urls url.split("?");if (urls[1]) {var arr urls[1].split("&");for …

【bzoj1070】[SCOI2007]修车 最小费用流

原文地址&#xff1a;http://www.cnblogs.com/GXZlegend/p/6798411.html 题目描述 同一时刻有N位车主带着他们的爱车来到了汽车维修中心。维修中心共有M位技术人员&#xff0c;不同的技术人员对不同的车进行维修所用的时间是不同的。现在需要安排这M位技术人员所维修的车及顺序…

“Assign Random Colors” is not working in 3ds Max 2015

Go to Customize -> Preferences…-> General (tab) Uncheck “Default to By Layer for New Nodes”转载于:https://www.cnblogs.com/cindy-hu-23/p/4476293.html

计算机编程课程顺序_您可以在6月开始参加630项免费的在线编程和计算机科学课程...

计算机编程课程顺序Six years ago, universities like MIT and Stanford first opened up free online courses to the public. Today, more than 800 schools around the world have created thousands of free online courses.六年前&#xff0c;麻省理工学院和斯坦福大学等大…