向GA4发送事件偶现TypeError: Failed to fetch问题排查求助
Service Worker中GA4事件推送部分失败(TypeError: Load failed/Failed to fetch)
我通过Service Worker在推送通知操作时发送自定义GA4事件,使用GA4官方的端点和参数。由于无法查看浏览器终端的错误信息,我将GA端点请求失败的错误日志记录到数据库中。目前95%的GA事件能成功发送,但仍有部分事件失败,日志显示为TypeError: Load failed或TypeError: Failed to fetch。
我个人无法复现该问题,自己触发的所有事件均发送成功,但部分网站用户会遇到此问题。我尝试排查设备或浏览器的共性,但该问题随机出现在Samsung Internet、Mobile Safari、Chrome Mobile等多种浏览器中,无明显规律。
我的Service Worker代码如下:
// ... // Triggered when push notification is closed self.addEventListener('notificationclose', event => { event.waitUntil(trackEvent('webpush_action', { action: 'Closed' })); }); async function trackEvent(name, params) { // ... const subscription = await self.registration.pushManager.getSubscription(); if (!subscription) { throw new Error('No subscription currently available.'); } try { const response = await fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, { method: 'POST', body: JSON.stringify({ client_id: subscription.endpoint, events: [{ name, params }] }) }); if (!response.ok) { throw new Error(await response.text()); } console.info('[Service Worker] Analytics event sent:', name); } catch (error) { const message = `[Service Worker] Unable to send the analytics event: ${error}`; console.warn(message); await logAnError(message); // just to log an error to my database for debugging purposes } }
我尝试在浏览器控制台执行fetch发送事件,故意传入错误的api_secret、client_id或事件数据,但始终返回204,无法复现该错误。
内容的提问来源于stack exchange,提问作者Ignas Damunskis
相关产品推荐
相关产品推荐

