You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Service Worker的push事件监听器未触发问题求助

自定义Service Worker的push事件监听器未触发问题求助

我最近在给Angular项目做iOS设备的通知角标功能,写了一个自定义的Service Worker来处理push事件设置角标,本地测试一切正常,但后端通过WebPushClient.SendNotificationAsync发送特定payload时,SW的push事件完全没触发,想请大家帮忙排查下问题。

我的实现代码:

  1. 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();
    }
  }
}
  1. 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));
  });
}
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 07:43:06