FCM
Firebase Cloud Messaging (FCM) 是一种跨平台消息传递解决方案,可供您可靠地传递消息。
主要支持 IOS Android Web
本篇文章主要介绍如何使用 fcm 向浏览器推送信息。也就是满足批量向浏览器客户端发送信息能力,并且浏览器不一定要一直打开网页。
#
使用FCM以步骤快速实现FCM-服务端向浏览器推送消息
#
fcm.html创建 fcm.html
页面并将 firebase 添加到项目中。 参考
下面代码主要内容
- 引入fcm相关依赖 其它方式可以参考引入Firebase SDK的各种方法
- 注册 fcm-sw.js (firebase-message-sw.js)
- 获取Token
注意这里需要fcm相关配置,具体配置信息可以看本文档的 《配置信息准备》 部分
<body> <button id="getToken">getToken</button> <script type="module"> import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js' import { getMessaging, getToken } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-messaging.js"
//配置firebase相关配置信息 const firebaseConfig = {}; // Initialize Firebase const app = initializeApp(firebaseConfig);
async function subscribe() { const messaging = getMessaging(app); //注册fcm-sw const sw = await navigator.serviceWorker.register("./fcm-sw.js"); //获取token const token = await getToken(messaging, {serviceWorkerRegistration: sw, vapidKey: 'BEERgraNf7qUCPuJuCuthyfiA_OhTgz3J_g4Qqb9TQLtX-PiQcptm6Sjf4Sj7cpqvrf8x44qBJq9vndy4vsYEJI' }).then((currentToken) => { if (currentToken) { // 成功得到token后,将其发送到后端保存,后续方便服务推送消息 console.log(currentToken) } else { // Show permission request UI console.log('No registration token available. Request permission to generate one.'); // ... } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); // ... }); } window.addEventListener("load",()=>{ document.getElementById("getToken").addEventListener('click',subscribe); }); </script></body>
#
fcm-sw.js创建 fcm-sw.js
service-work 脚本用于接收和展示信息。
- 使用
self.addEventListener('push',function)
监听消息 - 使用
self.registration.showNotification
来展示信息
self.addEventListener('install', function (event) { console.log("install", event) self.skipWaiting();// sw立即生效,并将之前的销毁})self.addEventListener('activate', function (event) { console.log("activate", event) //让没被控制的 clients(页面、workers) 受控, 否则要刷新页面才受控 self.clients.claim();})
/** * 消息点击 * @param {*} event */self.onnotificationclick = (event) =>{ clients.openWindow(event.notification.data.url);}
/** * 延时处理消息数据 */function p(){ setTimeout((()=>{ self.registration.getNotifications().then((o)=>{ o.forEach((e) => { console.log('notifications',e) e.close(); }); }) }),3600000)}
/** * 监听服务端发送的消息 */self.addEventListener('push', function (event) { //服务端发送消息内容 const data = event.data.json().data; console.log(data); event.waitUntil( //使用 notification 展示消息内容 self.registration.showNotification(data.title,{ body:data.body, //image 好像就window有用 image:data.image, icon:data.icon, data:{url:data.url}, //requireInteraction 消息窗不消失,必须点击 requireInteraction:true }).then(p) ) })
#
消息发送服务端可以通过 服务端参考文档 或者 Http协议参考 配置服务端账号(参考下图说明获取),根据用户授权的Token给浏览器推送信息
http 需要配置 Server Key
header 'Authorization: key=yourserverkey'
sdk 需要配置
serviceAccountKey.json
- CURL
- Java
curl --location --request POST 'https://fcm.googleapis.com/fcm/send' \--header 'Authorization: key=yourserverkey' \--header 'Content-Type: application/json' \--data-raw '{ "registration_ids": [ "yourtoken" ], "data": { "title": "tooltag", "body": "tooltag 在线文档|在线工具", "icon": "http://docs.tooltag.cn/img/logo.png", "image": "http://docs.tooltag.cn/img/logo.png", "url": "http://tooltag.cn" }}'
//包引入<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>8.1.0</version></dependency>
//消息发送public static void main(String[] args) throws Exception { //获取 serviceAccountKey InputStream serviceAccountKey = FcmDemo.class.getResourceAsStream("/serviceAccountKey.json"); FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccountKey)) .build(); FirebaseApp.initializeApp(options); Map map = new HashMap(); map.put("title","fcm title"); map.put("body","内容信息"); map.put("icon","http://docs.tooltag.cn/img/logo.png"); map.put("image","http://docs.tooltag.cn/img/logo.png"); map.put("url","http://tooltag.cn"); FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance(); //组织消息 Message messaging = Message.builder() .setToken("eDVw17QMP4IDSbyblGfCZw:APA91bE37dZE41dNIfVQdxelC9LWuf9mnKqY0lhgIO9f_PKO8cU4CvlEo5hGelXTBLpr_Cvq3H4cVkZQQmYT1nMt-CcS8VHJzuqn_z5wmhaRalESDC90ZNGylnFgef2ewyvUuc9qP-Wl") .putAllData(map) .build(); //发送消息 firebaseMessaging.send(messaging);}