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


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

    1. HTML 文件(index.html

    1. html>
    2. <html>
    3. <head>
    4. <title>FCM Push Notification Exampletitle>
    5. <script src="https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js">script>
    6. <script src="https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js">script>
    7. head>
    8. <body>
    9. <h1>Welcome to FCM Push Notification Exampleh1>
    10. <script src="main.js">script>
    11. body>
    12. html>

    2. 主 JavaScript 文件(main.js

    1. // Initialize Firebase
    2. firebase.initializeApp({
    3. apiKey: "your-api-key",
    4. authDomain: "your-auth-domain",
    5. projectId: "your-project-id",
    6. messagingSenderId: "your-messaging-sender-id",
    7. appId: "your-app-id"
    8. });
    9. const messaging = firebase.messaging();
    10. // Request permission and get token
    11. Notification.requestPermission().then((permission) => {
    12. if (permission === 'granted') {
    13. messaging.getToken().then((currentToken) => {
    14. if (currentToken) {
    15. console.log('Token:', currentToken);
    16. // Send this token to your server
    17. } else {
    18. console.log('No registration token available. Request permission to generate one.');
    19. }
    20. }).catch((err) => {
    21. console.log('An error occurred while retrieving token. ', err);
    22. });
    23. }
    24. });
    25. // Handle incoming messages
    26. messaging.onMessage((payload) => {
    27. console.log('Message received:', payload);
    28. // Customize notification here
    29. const notificationTitle = payload.notification.title;
    30. const notificationOptions = {
    31. body: payload.notification.body,
    32. icon: payload.notification.icon
    33. };
    34. new Notification(notificationTitle, notificationOptions);
    35. });

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

    1. // Import and configure the Firebase SDK
    2. importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js');
    3. importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');
    4. firebase.initializeApp({
    5. apiKey: "your-api-key",
    6. authDomain: "your-auth-domain",
    7. projectId: "your-project-id",
    8. messagingSenderId: "your-messaging-sender-id",
    9. appId: "your-app-id"
    10. });
    11. const messaging = firebase.messaging();
    12. // Handle background messages
    13. messaging.onBackgroundMessage((payload) => {
    14. console.log('Received background message:', payload);
    15. const notificationTitle = payload.notification.title;
    16. const notificationOptions = {
    17. body: payload.notification.body,
    18. icon: payload.notification.icon
    19. };
    20. self.registration.showNotification(notificationTitle, notificationOptions);
    21. });
    22. // Handle notification click
    23. self.addEventListener('notificationclick', (event) => {
    24. event.notification.close();
    25. event.waitUntil(
    26. clients.openWindow('https://fbspider.com')
    27. );
    28. });

     

    4. 在服务器端发送推送

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

    1. curl -X POST "https://fcm.googleapis.com/fcm/send" \
    2. -H "Authorization: key=your-server-key" \
    3. -H "Content-Type: application/json" \
    4. -d '{
    5. "to": "client-token",
    6. "notification": {
    7. "title": "Your Title",
    8. "body": "Your Body",
    9. "icon": "your-icon-url"
    10. }
    11. }'

    这个示例包括:

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

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

  • 相关阅读:
    Adobe Acrobat Pro DC 2023:提升工作效率,激发创意灵感 mac/win版
    翻译软件-免费翻译软件-自动批量翻译软件
    06 文件和异常
    web页面拦截用户登录,管理session和cookie
    2025武忠祥考研数学,视频百度网盘+基础全程课程PDF
    GRACE球谐数据滤波处理(利用matlab实现GRACE月水储量的二维傅里叶变化滤波)
    企业如何做好疫情防控?数字化疫情管理事半功倍
    萌新卷妹带你逃出算法无名岛第六站
    IDEA 打包MapReduce程序到集群运行的两种方式以及XShell和Xftp过期的解决
    搞懂 冒泡排序原理 锁和事务的原理(图文并茂)
  • 原文地址:https://blog.csdn.net/kevin_lcq/article/details/133760063