Firebase Web Push通知点击/打开计数不统计问题解决咨询
解决Firebase Web Push点击计数为0及Service Worker统计问题
一、修复点击/打开计数为0的核心思路
Firebase默认的通知点击计数依赖客户端Analytics SDK,但Service Worker环境下无法直接初始化SDK,得通过「Service Worker传参+客户端页面上报」的方式补统计:
- 在Service Worker里监听通知点击事件,把推送的
messageId通过URL参数传递到打开的页面 - 页面加载后,用客户端Analytics的
logEvent上报notification_open事件,并带上messageId参数
示例代码实现
Service Worker中处理点击事件
self.addEventListener('notificationclick', (event) => { event.notification.close(); // 从通知data中取messageId(需在推送时携带该字段) const messageId = event.notification.data?.messageId; // 打开页面并携带messageId参数 event.waitUntil( clients.openWindow(`/?notifyId=${messageId}`) ); });
页面客户端上报统计
import { getAnalytics, logEvent } from "firebase/analytics"; // 页面初始化时检查URL参数 const urlParams = new URLSearchParams(window.location.search); const notifyId = urlParams.get('notifyId'); if (notifyId) { const analytics = getAnalytics(); // 上报通知打开事件,携带messageId logEvent(analytics, 'notification_open', { message_id: notifyId, // 可额外添加通知标题、类型等自定义参数 }); // 移除URL参数避免重复上报 urlParams.delete('notifyId'); window.history.replaceState({}, document.title, `${window.location.pathname}${urlParams.toString() ? `?${urlParams.toString()}` : ''}`); }
二、Service Worker内直接上报的替代方案
如果不想依赖页面加载,可直接调用Firebase Measurement Protocol(REST接口)在Service Worker内上报:
- 提前在Firebase控制台获取你的
measurement_id和api_secret - 确保能获取用户的
client_id(可在客户端缓存到IndexedDB,或推送时携带在data中)
示例请求代码
self.addEventListener('notificationclick', async (event) => { event.notification.close(); const messageId = event.notification.data?.messageId; const measurementId = 'G-XXXXXX'; // 替换为你的Analytics测量ID const apiSecret = 'your-api-secret'; // 替换为控制台获取的API密钥 const clientId = await getClientIdFromStorage(); // 自定义方法,从存储取client_id await fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, { method: 'POST', body: JSON.stringify({ client_id: clientId, events: [{ name: 'notification_open', params: { message_id: messageId } }] }) }); event.waitUntil(clients.openWindow('/')); });
三、注意事项
messageId需要在推送时主动携带:通过Firebase控制台发送时,在「高级选项-自定义数据」里添加messageId字段;后端推送时在data参数中传入- 避免重复上报:页面上报后记得清理URL参数,Service Worker上报可加幂等校验
内容的提问来源于stack exchange,提问作者Abylay
相关产品推荐
相关产品推荐

