• 基于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 配置和服务器密钥。希望这个示例能帮助你!

  • 相关阅读:
    实在智能出席山东省数据科学大会,构建产学研教数智创新生态
    在listener.ora配置文件中配置listener 1527的监听并且使用tnsnames连接测试
    使用Scala和Sttp库编写爬虫程序
    体细胞杂交第六弹!worthington组织培养术语终章
    音频的传输链路与延迟优化点
    m在ISE平台下使用verilog开发基于FPGA的GMSK调制器
    Android 自动取色并设置沉浸式状态栏
    LeetCode刷题 309 :最佳买卖股票的时机含冷冻时期
    头歌平台 第2关:整数四则运算表达式的输出格式控制
    【C++】命名空间
  • 原文地址:https://blog.csdn.net/kevin_lcq/article/details/133760063