Skip to main content

FCM

Firebase Cloud Messaging (FCM) 是一种跨平台消息传递解决方案,可供您可靠地传递消息。 主要支持 IOS Android Web
本篇文章主要介绍如何使用 fcm 向浏览器推送信息。也就是满足批量向浏览器客户端发送信息能力,并且浏览器不一定要一直打开网页。

使用FCM#

以步骤快速实现FCM-服务端向浏览器推送消息

fcm.html#

创建 fcm.html 页面并将 firebase 添加到项目中。 参考 下面代码主要内容

  1. 引入fcm相关依赖 其它方式可以参考引入Firebase SDK的各种方法
  2. 注册 fcm-sw.js (firebase-message-sw.js)
  3. 获取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 脚本用于接收和展示信息。

  1. 使用 self.addEventListener('push',function) 监听消息
  2. 使用 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 --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"    }}'

配置信息准备#

1. 进入firebase console 创建新的项目#

2. 进入项目创建 web app#

3. 获取前端使用firebase config#

4. 获取VAPID#

5. 获取Server Key#

6. 获取Server Key JSON#