当前位置: 首页 > news >正文

基于Google‘s FCM实现消息推送

当然,下面是一个简单的示例,演示了如何使用 Service Worker 和 Google's Firebase Cloud Messaging(FCM)来实现 Web 推送通知。

1. HTML 文件(index.html

<!DOCTYPE html>
<html>
<head><title>FCM Push Notification Example</title><script src="https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js"></script><script src="https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js"></script>
</head>
<body><h1>Welcome to FCM Push Notification Example</h1><script src="main.js"></script>
</body>
</html>

2. 主 JavaScript 文件(main.js

// Initialize Firebase
firebase.initializeApp({apiKey: "your-api-key",authDomain: "your-auth-domain",projectId: "your-project-id",messagingSenderId: "your-messaging-sender-id",appId: "your-app-id"
});const messaging = firebase.messaging();// Request permission and get token
Notification.requestPermission().then((permission) => {if (permission === 'granted') {messaging.getToken().then((currentToken) => {if (currentToken) {console.log('Token:', currentToken);// Send this token to your server} else {console.log('No registration token available. Request permission to generate one.');}}).catch((err) => {console.log('An error occurred while retrieving token. ', err);});}
});// Handle incoming messages
messaging.onMessage((payload) => {console.log('Message received:', payload);// Customize notification hereconst notificationTitle = payload.notification.title;const notificationOptions = {body: payload.notification.body,icon: payload.notification.icon};new Notification(notificationTitle, notificationOptions);
});

3. Service Worker 文件(firebase-messaging-sw.js

// Import and configure the Firebase SDK
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');firebase.initializeApp({apiKey: "your-api-key",authDomain: "your-auth-domain",projectId: "your-project-id",messagingSenderId: "your-messaging-sender-id",appId: "your-app-id"
});const messaging = firebase.messaging();// Handle background messages
messaging.onBackgroundMessage((payload) => {console.log('Received background message:', payload);const notificationTitle = payload.notification.title;const notificationOptions = {body: payload.notification.body,icon: payload.notification.icon};self.registration.showNotification(notificationTitle, notificationOptions);
});// Handle notification click
self.addEventListener('notificationclick', (event) => {event.notification.close();event.waitUntil(clients.openWindow('https://fbspider.com'));
});

 

4. 在服务器端发送推送

使用 cURL 或其他 HTTP 客户端发送一个 POST 请求:

curl -X POST "https://fcm.googleapis.com/fcm/send" \-H "Authorization: key=your-server-key" \-H "Content-Type: application/json" \-d '{"to": "client-token","notification": {"title": "Your Title","body": "Your Body","icon": "your-icon-url"}}'

这个示例包括:

  • 初始化 Firebase 和消息传递服务。
  • 请求用户权限并获取 FCM 令牌。
  • 在前台和后台接收消息。
  • 点击通知后跳转到 https://fbspider.com

请确保替换所有的 your-* 占位符为你自己的 Firebase 配置和服务器密钥。希望这个示例能帮助你!

http://www.lryc.cn/news/188377.html

相关文章:

  • 若依微服务前后端部署启动流程(只记录)
  • docker创建nginx容器
  • nio 文件传输
  • 2023-10-09 python-安装psd_tools-记录
  • 【Python目标识别】目标检测的原理及常见模型的介绍
  • SpringCloud小项目——订单积分商城 使用Nacos、Open Feign、Gateway、Sentinel技术栈
  • 澳大利亚教育部宣布ChatGPT将被允许在澳学校使用!
  • Linux基础指令笔记大全
  • vue学习-14vue的路由缓存组件以及activated和deactivated生命周期钩子
  • 【opencv】windows10下opencv4.8.0-cuda版本源码编译教程
  • 31 数据分析(中)numpy介绍
  • 华为OD机考算法题:字符串划分
  • AF_UNIX和127.0.0.1(AF_INET)回环地址写数据速度对比(二)
  • “Python+”集成技术高光谱遥感数据处理与机器学习教程
  • centos7 快速搭建自测mysql环境 docker + mysql
  • c++视觉检测-----Canny边缘算子
  • 机器学习笔记 - 用于动作识别的网络TSN/TSM/SlowFast/R(2+1)D/3D MobileNetV2
  • mybatis批量插入
  • 软件‘小程序‘前台开发软件定制的知识|app网站搭建
  • HTML-注册页面
  • 17.(开发工具篇Gitlab)如何在Gitlab配置ssh key
  • ArcGIS/GeoScene脚本:基于粒子群优化的支持向量机分类模型
  • Python+Tkinter 图形化界面基础篇:添加图形和图像
  • 前端js八股文大全
  • [环境]Ubuntu20.04安装Ceres
  • ruoyi 若依 前端vue npm install 运行vue前端
  • 各大搜索引擎的User-Agent
  • codesys【按钮】
  • SSH在桌面会话启动应用程序
  • React的类式组件和函数式组件之间有什么区别?