Web端Firebase Cloud Messaging无法接收消息求助
FCM Web集成问题:获取Token后无法接收测试消息
我正在学习Firebase Cloud Messaging (FCM),打算先搭建一个简单示例,再集成到基于Apache+PHP服务端、Javascript客户端的主项目中。按官方步骤完成了JS客户端设置和接收消息的配置,已成功获取Token,但发送测试消息后客户端无任何反应,onMessage处理器未触发。
现有代码
index.php
<body> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js"; import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging.js"; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "AI......hidden......po", authDomain: "fcm-notification-dxxxx.firebaseapp.com", projectId: "fcm-notification-dxxxx", storageBucket: "fcm-notification-dxxxx.appspot.com", messagingSenderId: "6......hidden......8", appId: "1:6......hidden......8:web:0......hidden......9" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const messaging = getMessaging(app); Notification .requestPermission() .then((permission) => { if(permission === 'granted') { console.log('Notification permission granted.'); getToken(messaging, { vapidKey: "BP......hidden......a8" }) .then((currentToken) => { if (currentToken) { console.log("Got current token."); console.log(currentToken); } else { console.log('No registration token available. Request permission to generate one.'); } }) .catch((err) => { console.log('An error occurred while retrieving token. ', err); }); } }); onMessage(messaging, (payload) => { console.log('Message received. ', payload); new Notification(payload.notification.title, payload.notification); }); </script> </body>
firebase-messaging-sw.js
位于localhost根目录,当前为空脚本
已确认情况
- 通过Chrome开发者工具已成功获取FCM Token:

问题
向获取到的Token发送测试通知后,客户端无任何反应,预期onMessage会在控制台打印消息payload,但未触发。
修正方案
1. 完善Service Worker脚本
空的Service Worker无法处理FCM消息,需要导入Firebase SDK并初始化:
importScripts('https://www.gstatic.com/firebasejs/9.14.0/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging-compat.js'); const firebaseConfig = { apiKey: "AI......hidden......po", authDomain: "fcm-notification-dxxxx.firebaseapp.com", projectId: "fcm-notification-dxxxx", storageBucket: "fcm-notification-dxxxx.appspot.com", messagingSenderId: "6......hidden......8", appId: "1:6......hidden......8:web:0......hidden......9" }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); // 处理后台消息(页面未聚焦时) messaging.onBackgroundMessage((payload) => { console.log('[firebase-messaging-sw.js] Received background message ', payload); const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, icon: '/firebase-logo.png' // 可替换为你的通知图标路径 }; self.registration.showNotification(notificationTitle, notificationOptions); });
2. 添加Service Worker注册逻辑
在index.php的脚本中,初始化Firebase后添加注册代码,确保Service Worker与FCM关联:
// 注册Service Worker if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/firebase-messaging-sw.js') .then((registration) => { console.log('ServiceWorker registration successful with scope: ', registration.scope); messaging.useServiceWorker(registration); }) .catch((err) => { console.log('ServiceWorker registration failed: ', err); }); }); }
3. 检查测试消息格式
确保测试消息包含notification字段,若通过Firebase控制台发送,需选择"Web"平台,填写正确Token,且消息包含标题和正文。
4. 验证运行环境
FCM要求Web应用运行在HTTPS环境下(localhost为例外,可正常测试),生产环境必须使用HTTPS。
5. 确认页面状态
- 测试前台消息时,需保持页面处于浏览器前台
- 后台消息由Service Worker处理,需确保Service Worker已正常注册
内容的提问来源于stack exchange,提问作者Ray Yen
相关产品推荐
相关产品推荐

