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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值