firebase推送

This article will help you implement firebase web push notifications without using any packages in your project for latest version 7.18.0 or above.

本文将帮助您实现Firebase Web推送通知,而无需在项目中使用最新版本7.18.0或更高版本的任何程序包。

介绍 (INTRODUCTION)

Firebase uses cloud services for its notification services on Android,IOS & Web.Firebase Cloud Messaging or FCM run on basic principles of tokens, which is uniquely generated for each device & later used for sending messages to respective devices.

Firebase在Android,IOS和Web上的通知服务使用云服务.Firebase Cloud Messaging或FCM基于令牌的基本原理运行, 令牌是为每个设备唯一生成的,后来用于向各个设备发送消息。

Web Push Notification uses javascript to call firebase methods and generate the token.This article will explain how to implement firebase cloud messaging ,right from setting up project.

Web Push Notification使用javascript调用firebase方法并生成令牌。本文将直接从设置项目开始,说明如何实现firebase云消息传递。

Note-FCM only works for Https server

Note-FCM仅适用于Https服务器

1.注册Firebase应用 (1.Register Firebase App)

  1. Go to link https://console.firebase.google.com/u/0/ and click create project.

    转到链接https://console.firebase.google.com/u/0/ ,然后单击创建项目。

2.Enter your project name ,& continue once name is checked by google for its uniqueness

2.输入项目名称,一旦Google检查了名称的唯一性,请继续

3.Enter the information asked such as country and accept terms & conditions and continue.Wait for some time till project is created.

3.输入询问的信息(例如国家/地区)并接受条款和条件并继续。请等待一段时间直到创建项目。

4.Add app to your project,it can be anything from Android,IOS,Web,Unity.For this article we need web app so click on web icon represented as </>

4.添加应用程序到您的项目中,它可以是Android,IOS,Web,Unity中的任何内容。对于本文,我们需要Web应用程序,因此请单击表示为</>的Web图标

5.Add a nick-name to your app,this nick-name is only for user and internal use ,which means it is useful just to differentiate between apps in a project from perspective of user.

5.为您的应用程序添加一个昵称,该昵称仅供用户和内部使用,这意味着从用户角度区分项目中的应用程序很有用。

You can add hosting for project if your project is already not running on https server else you can skip this step.

如果您的项目尚未在https服务器上运行,则可以为项目添加托管,否则可以跳过此步骤。

Click on Register app

点击注册应用

6.After your app is Registered you will be presented with Firebase SDK,which look like the code written below,you may copy this now,if not it can also be used later from settings,steps for which will be described in next section.

6.注册您的应用程序后,您将看到Firebase SDK,它看起来像下面的代码,您可以立即复制它,如果没有,也可以在以后的设置中使用,有关步骤将在下一节中介绍。

<!-- The core Firebase JS SDK is always required and must be listed first --><script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script>General<!-- TODO: Add SDKs for Firebase products that you want to use     https://firebase.google.com/docs/web/setup#available-libraries -->For Messaging<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js"></script>Do not copy below code as it is,values will be different for your app.<script>  // Your web app's Firebase configuration    var firebaseConfig = {  apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",  authDomain: "myapp-project-123.firebaseapp.com",  databaseURL: "https://myapp-project-123.firebaseio.com",  projectId: "myapp-project-123",  storageBucket: "myapp-project-123.appspot.com",  messagingSenderId: "65211879809",  appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",};  };  // Initialize Firebase  firebase.initializeApp(firebaseConfig);</script>

2.将Firebase添加到您的项目中。 (2.Add firebase to your Project.)

  1. On dashboard , go to you side bar and click settings icon.Refer image below.Click project Settings.

    在信息中心上,转到侧边栏,然后单击设置图标。 请参考下图。 单击项目设置。

2.Once Setting page(General Settings) is opened you scroll down to bottom of page and copy the code displayed for CDN selected.

2.打开设置页面(常规设置)后,向下滚动到页面底部,然后复制为所选CDN显示的代码。

3.Add this code to your HTML file at the end after body tag and add CDN script for firebase messaging , as shown in code below.

3.将此代码添加到body标记后的末尾HTML文件中,并添加用于Firebase消息传递的CDN脚本,如以下代码所示。

<body>--------Your Page Contents----</body><script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script><script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js"></script>//Do not copy below code as it is values will be different for your app.<script>// Your web app's Firebase configuration    var firebaseConfig = {  apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",  authDomain: "myapp-project-123.firebaseapp.com",  databaseURL: "https://myapp-project-123.firebaseio.com",  projectId: "myapp-project-123",  storageBucket: "myapp-project-123.appspot.com",  messagingSenderId: "65211879809",  appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",};  }; // Initialize Firebase  firebase.initializeApp(firebaseConfig);</script>

3.运行Firebase服务 (3.Running Firebase Service)

  1. For the code mentioned above, add the lines in code below ,after firebase initialize line.对于上述代码,在firebase初始化行之后,在下面的代码中添加行。
// Initialize Firebasefirebase.initializeApp(firebaseConfig);const messaging=firebase.messaging();//Custom function made to run firebase service getStartToken();//This code recieve message from server /your app and print message to console if same tab is opened as of project in browser messaging.onMessage(function(payload){console.log("on Message",payload);});

2.The code below can be written in separate js file included in your html page or can be appended to code above in <script> tag.

2.下面的代码可以写在HTML页面中包含的单独的js文件中,也可以在<script>标记中附加到上面的代码中。

messaging.getToken() retrieves token by called firebase sdk,if token is found ,we send it to server for storage,else we ask for permission to user to send him notification by calling method RequestPermission(),which is custom function.

messages.getToken()通过调用firebase sdk检索令牌,如果找到令牌,则将其发送到服务器进行存储,否则我们通过调用方法RequestPermission()来请求用户向他发送通知,该方法是自定义函数。

setTokenSentToServer() is also a custom function which uses local storage to set value of sendTokenToServer==1 if token is already sent to server and 0 if token is not sent to server some error is occured while sending to sever or retrieving it from firebase SDK

setTokenSentToServer()也是一个自定义函数,如果令牌已发送到服务器,则使用本地存储设置sendTokenToServer的值== 1;如果令牌未发送到服务器,则设置为0;如果将令牌发送到服务器或从Firebase SDK检索,则会发生一些错误

function getStartToken(){messaging.getToken().then((currentToken) => {if (currentToken) {sendTokenToServer(currentToken);} else {// Show permission request.RequestPermission();setTokenSentToServer(false);}}).catch((err) => {setTokenSentToServer(false);});}function RequestPermission(){messaging.requestPermission().then(function(permission){if (permission === 'granted') {console.log("have Permission");//calls method again and to sent token to servergetStartToken(); } else{console.log("Permission Denied");}.catch(function(err){console.log(err);})}function sendTokenToServer(token){ if (!isTokensendTokenToServer()) {$.ajax({url: URL,type: 'POST',data: {//whatever you wanna sendpush_token:token,},success: function (response) {setTokenSentToServer(true);},error: function (err) {setTokenSentToServer(false);},});}}function isTokensendTokenToServer() {return window.localStorage.getItem('sendTokenToServer') === '1';}function setTokenSentToServer(sent) {window.localStorage.setItem('sendTokenToServer', sent ? '1' : '0');}

3.从项目发送消息 (3.Send Message from Project)

1.Sending Mesaging Pre-requirements

1. 发送消息预定要求

a.For vapidKey go to settings on firebase console,click cloud messaging ,scroll down to bottom of page in Web Configuration section click on button Generate Key Pair.

对于vapidKey,请转到firebase控制台上的设置单击“云消息传递”然后在“ Web配置”部分中向下滚动到页面底部,单击“ 生成密钥对”按钮

b.Code to send message from your project ,refer Google on how to send API request from your respective programming language.

b。从您的项目发送消息的代码,请向Google咨询如何从您各自的编程语言发送API请求。

METHOD-POST

方法

URL-https://fcm.googleapis.com/fcm/send

网址-https : //fcm.googleapis.com/fcm/send

HEADERS-send with authorization using key which can be found on Settings>Cloud Messaging,look for project credentials section and copy server key.

HEADERS- 使用密钥发送授权,该密钥可以在“设置”>“云消息”中找到,查找项目凭证部分并复制服务器密钥。

to-Token you saved on in your database for user .

to- Token,您保存在数据库中供user使用。

registeration_ids-if sending to multiple device

registeration_ids- 如果发送到多个设备

c.To read about diiferent messages and fcm_options you can refer to this url https://firebase.google.com/docs/cloud-messaging/concept-options

c。要了解有关不同消息和fcm_options的信息,请参阅以下网址https://firebase.google.com/docs/cloud-messaging/concept-options

d.If you want send in FCM notifications in you format you can refer to link https://firebase.google.com/docs/cloud-messaging/js/first-message and see notification message format

d。如果要以您的格式发送FCM通知,可以参考链接https://firebase.google.com/docs/cloud-messaging/js/first-message并查看通知消息格式

e.for this article i will be using data messages/custom/without predefined key-value pairs.

e。 对于本文,我将使用数据消息/自定义/没有预定义的键值对。

Note-Data send is json format

注意-数据发送为json格式

f.my data look like

F。 我的数据看起来像

{"registration_ids":{token1,token2,token3},"data":{ "title":"demo","body":this is demo data","clickUrl":"https://google.com"}}

5,增加服务人员 (5.Add Service Worker)

  1. Add a Service-Worker file by name (don’t change the name) firebase-messaging-sw.js in your project root folder or public folder such as opening link-https://your-url/firebase-messaging-sw.js gives you content of file.

    在您的项目根文件夹或公用文件夹(例如, 打开链接 -https :// your-url / firebase-messaging-sw )中,按名称( 不要更改名称 )添加fire-worker文件firebase-messaging-sw.js 。 js 给你文件的内容。

  2. payload is data you send you recieve when api request will be sent.有效负载是您将在api请求发送时收到的数据。
  3. You will not require notification event listener if message is send through standard FCM notification message ,fcm will handle it itself.如果通过标准FCM通知消息发送消息,则不需要通知事件侦听器,fcm会自行处理。
importScripts('https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js');importScripts('https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js');// Your web app's Firebase configuration    var firebaseConfig = {  apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",  authDomain: "myapp-project-123.firebaseapp.com",  databaseURL: "https://myapp-project-123.firebaseio.com",  projectId: "myapp-project-123",  storageBucket: "myapp-project-123.appspot.com",  messagingSenderId: "65211879809",  appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",};firebase.initializeApp(firebaseConfig);const messaging = firebase.messaging();messaging.usePublicVapidKey(ABp.........BS5A);messaging.onBackgroundMessage(function(payload) {const notificationTitle = payload.data.title;const notificationOptions = {body: payload.data.message,icon:'PATH TO ICON IF ANY',data: { url:payload.data.onClick }, //the url which we gonna use later};return self.registration.showNotification(notificationTitle,notificationOptions);});//Code for adding event on click of notificationself.addEventListener('notificationclick', function(event) {let url = event.notification.data.url;event.notification.close(); event.waitUntil(clients.matchAll({type: 'window'}).then( windowClients => {// Check if there is already a window/tab open with the target URLfor (var i = 0; i < windowClients.length; i++) {var client = windowClients[i];// If so, just focus it.if (client.url === url && 'focus' in client) {return client.focus();}}// If not, then open the target URL in a new window/tab.if (clients.openWindow) {return clients.openWindow(url);}}));});

这些是将Firebase Web Push添加到项目中所需的唯一步骤。 (These are the only steps you will need to add firebase web push to your project.)

Press Clap if this article really helped you.

如果本文确实对您有帮助,请按Clap。

翻译自: https://medium.com/analytics-vidhya/firebase-web-push-notifications-26352b136814

firebase推送


http://www.taodudu.cc/news/show-4983671.html

相关文章:

  • 如何使用 PHP 发送 Web 推送通知
  • 7种 实现web实时消息推送的方案
  • Web消息推送之SSE
  • Web服务器推送信息SSE/WebSocket
  • 内存修改器
  • 新天骄2912服务器 修改,叶舞秦殇2019.2.13
  • BIGEMAP使用Bigemap下载地图生成GST(Mapinfo格式)地图包
  • 编译错误error: invalid storage class
  • 如何监听storage仓库变化(只限localstorage)
  • Vue封装local及session
  • WSL自定义并加入usb-storage module
  • 016基于pinia完成Vue3的前端数据持久化储存storage的方案落地
  • pinia个人学习笔记
  • MinIO 对象存储
  • cookie和storage
  • Spark (一):Executor内存
  • [engine]加载速度拉满的direct storage
  • 基于localStorge开发登录模块的记住密码与自动登录
  • 使用Storage实现登录弹出
  • 重庆计算机考试怎么才算过,@重庆考生 中高考电脑阅卷流程是这样的 注意细节可多拿分...
  • 中职计算机高考提分技巧,高考前提分技巧:熟悉高考电脑阅卷流程 让你多拿20分...
  • 孩子误了计算机考试能参加中考吗,看完中考电脑阅卷“内幕”,你还会让孩子这样答卷吗?...
  • 计算机中考在线评分卡,重磅!中考电脑阅卷流程曝光!认真读完至少多拿20分!...
  • 高中计算机阅卷要求,给考生:了解中考电脑阅卷规则,读完多拿20分!
  • 中考计算机专业如果忘了怎么办,真实的电脑阅卷告诉你,这样做中考可以少丢分!...
  • 2020中考可不可以用计算机,2020中考必读 | 中考电脑阅卷流程“潜规则”!读完孩子少丢20分!(转给中考生)...
  • 高考改卷中使用了大量计算机,中高考电脑阅卷原来是这样的!认真看多拿分!...
  • 中考不能用计算机ka,中考电脑阅卷“内幕”,你的孩子都注意到了吗?
  • 中考计算机考试试题2018,2018年中招考试电脑阅卷流程曝光,你一定要知道
  • 英特尔的“尺子”,三星的“钉子”

firebase推送_Firebase Web推送通知相关推荐

  1. JavaScript是如何工作的:Web推送通知的机制

    这是专门探索 JavaScript 及其所构建的组件的系列文章的第9篇. 如果你错过了前面的章节,可以在这里找到它们: JavaScript是如何工作的:引擎,运行时和调用堆栈的概述! JavaScr ...

  2. 如何使用 PHP 发送 Web 推送通知

    Web Push API 允许您向 Web 浏览器和 API 发送推送通知.虽然大部分逻辑发生在浏览器中,但您仍然需要一个服务器端组件来生成通知.以下是使用 PHP 实现 Web 推送后端的方法. 先 ...

  3. JavaScript是如何工作的: Web推送通知的机制

    摘要: 如何在Web端推送消息? 原文:JavaScript是如何工作的: Web推送通知的机制 作者:前端小智 Fundebug经授权转载,版权归原作者所有. 这是专门探索 JavaScript 及 ...

  4. firebase 云推送_使用Firebase云消息传递在Android中推送通知

    firebase 云推送 这篇文章介绍了如何在Android中发送推送通知 . 过去,我们曾经使用Google Cloud消息传递服务在Android中发送推送通知. 最近,它引入了一种使用Fireb ...

  5. 【PWA】web推送技术

    伴随着今年 Google I/O 大会的召开,一个很火的概念–Progressive Web Apps 诞生了.这代表着我们 web 端有了和原生 APP 媲美的能力.但是,有一个很重要的痛点,web ...

  6. Azure SignaIR 将数据从服务器实时推送到Web 和移动浏览器、桌面应用、移动应用等客户端

    本文章完整免费视频讲解地址: Azure SignaIR-向各种客户端实时推送 常规的推送技术:Websocket /服务器发送事件 (SSE) /长轮询等其他技术. ​ SignaIR存在了很长的历 ...

  7. Asp.net SignalR 实现服务端消息推送到Web端

    参考博客https://www.cnblogs.com/wintersun/p/4148223.html ASP .NET SignalR是一个ASP .NET 下的类库,可以在ASP .NET 的W ...

  8. 海康大华等安防摄像机采用通用RTSP协议流转RTMP推送至Web无插件播放展示的流程方法

    行业现状 中国互联网化的进程已经越来越快了,各个行业都在进行着互联网化的改造,流媒体.音视频,作为跑在互联网上最大量级的数据类型,其从编码方式到传输协议到终端兼容都成为各家标准抢占的高点,RTMP.H ...

  9. 基于极光推送的web,app消息系统

    设计要点 1.web,app注册系统同时注册极光IM 2.WEB集成IM sdk,用户WEB登录与极光IM建立长连接 3.后端调用极光IM API给WEB用户推送消息,并将信息存入持久化到DB 4.用 ...

最新文章

  1. javaweb实现mysql备份功能_java web 实现mysql 数据库备份、恢复
  2. lnmp mysql 哪个好_lamp与lnmp的选择
  3. python语音控制智能家电_Python 树莓派智能音箱语音控制电脑开关机-Python 实用宝典...
  4. vs2010连接mongodb服务器,X64位
  5. ionic ui框架及creator使用帮助
  6. 光电转换器有什么作用?光纤收发器如何保养?
  7. 【Git、GitHub、GitLab】五 git中裸仓库.git下的内容
  8. 回文数-时间变换-判断邮箱
  9. 2019java形势,2019Java开发还有哪些发展
  10. DAS 2020 Keynote Speech | 深度学习时代的 OCR
  11. 环境安装_Python教程 Python环境安装
  12. python一些常用方法_收藏整理的一些Python常用方法和技巧
  13. 3.JUC线程高级-同步容器 ConcurrentHashMap
  14. 换热站实际应用程序:西门子200smart PLC与威纶通触摸屏换热站程序、西门子1200plc与昆仑通态触摸屏换热站程序
  15. 【线性代数】P6 矩阵的幂转置特殊矩阵
  16. 收集一些Qt学习网站
  17. 免费下载百度 豆丁 丁香 等平台文档
  18. pdf转cad格式工具控件pdf2cad
  19. chromium os系统编译与环境搭建
  20. Python-png转换成jpg

热门文章

  1. pymongo获取一列数据
  2. 室内聚会趣味游戏大全
  3. 优秀开源产品推荐:Tpflow工作流引擎
  4. Linux C语言编写2048小游戏
  5. LeetCode(python3)——234.回文联表
  6. 关于新手学习帝国之类的CMS工具建议
  7. 客户端架构(C/S架构和B/S架构)
  8. Visual Studio 2019无法打开源文件
  9. 关于《梦回水浒》的几个问题释疑
  10. 接口快速复制到 Postman 接口快速修改参数调试