自定义Service Worker的push事件监听器未触发问题求助
自定义Service Worker的push事件监听器未触发问题求助
我最近在给Angular项目做iOS设备的通知角标功能,写了一个自定义的Service Worker来处理push事件设置角标,本地测试一切正常,但后端通过WebPushClient.SendNotificationAsync发送特定payload时,SW的push事件完全没触发,想请大家帮忙排查下问题。
我的实现代码:
- iphone-notification-badge-worker.js 代码
self.addEventListener("push", (event) => { console.log('Push event received!!!!'); const data = event.data ? event.data.json() : {}; if (data?.badgeCount !== undefined) { event.waitUntil(setBadgeCount(data.badgeCount)); } }); async function setBadgeCount(badgeCount) { if (self.registration.setAppBadge) { if (badgeCount && badgeCount > 0) { await self.registration.setAppBadge(badgeCount); } else { await self.registration.clearAppBadge(); } } }
- main.ts 中的SW注册代码
if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('iphone-notification-badge-worker.js') .then(reg => console.log('Custom SW registered', reg)) .catch(err => console.error('Custom SW registration failed', err)); }); }
- angular.json 中的build配置(assets部分)
我已经把SW文件加入了打包资产列表,确保生产构建时会输出到dist目录:
"architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist", "index": "src/index.html", "browser": "src/main.ts", "polyfills": ["zone.js"], "tsConfig": "tsconfig.app.json", "inlineStyleLanguage": "scss", "assets": [ "src/favicon.ico", "src/assets", "src/manifest.webmanifest", "src/robots.txt", "src/block-robots.txt", "src/iphone-notification-badge-worker.js" ], // 其他配置... } } }
测试情况:
- 本地用production配置运行项目时,SW能正常注册,在Chrome DevTools的
Inspect > Service Workers面板手动发送{badgeCount:3}的push消息,SW里的console.log能正常输出,角标也能正确设置,功能完全正常。 - 后端用
WebPushClient.SendNotificationAsync发送带notification字段的payload时(比如:{"notification": {"title": "Test titel","body": "Test content"}}),设备能正常收到系统通知,说明VAPID密钥、用户订阅信息都是正确的。 - 但如果后端发送仅包含
badgeCount的payload:{"badgeCount": 3},设备完全没有反应,SW里的断点和console.log都没触发,仿佛这个push消息根本没到达SW。
想请教大家:为什么这种情况下push事件监听器不触发?是不是payload的格式有要求,或者Angular的打包/注册还有什么遗漏的配置?
内容来源于stack exchange
相关产品推荐
相关产品推荐

