如何在浏览器中监听Azure Notifications Hub事件?请求故障排查协助
排查Azure Notification Hub浏览器推送失败问题
1. 验证VAPID密钥配置与使用一致性
- 确保前端
applicationServerKey使用的是Base64 URL编码的VAPID公钥,不要直接使用原始字节公钥(需转换为去掉末尾等号、替换+为-、/为_的格式)。 - 确认Azure Portal中Notification Hub配置的VAPID私钥,与前端使用的公钥是配对生成的密钥对。
2. 完善浏览器注册流程
- 你的前端代码仅完成了浏览器推送订阅,未将订阅信息提交到Azure Notification Hub完成注册。需在
subscription回调中,把endpoint、keys.p256dh、keys.auth三个字段,通过REST API提交到Hub:sw.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: "BASE64_URL_ENCODED_VAPID_PUBLIC_KEY" }).then((subscription) => { // 构造请求数据并调用Azure注册API const registrationData = { Endpoint: subscription.endpoint, P256DH: subscription.keys.p256dh, Auth: subscription.keys.auth }; // 此处添加POST请求到Azure Notification Hub注册API的代码 }); - 提交REST API时需注意:
- 请求头必须包含
Authorization(SAS Token)和Content-Type: application/atom+xml;type=entry;charset=utf-8。 <Endpoint>字段必须完全匹配订阅返回的endpoint值,不能截断或修改。<P256DH>和<Auth>必须使用订阅返回的原始值,不要做编码或格式修改。
- 请求头必须包含
3. 修正Service Worker配置
- 确保
service-worker.js放在网站根目录下,若需放在子目录,注册时需指定作用域:navigator.serviceWorker.register("/subdir/service-worker.js", { scope: "/" }); - 给
push事件添加错误捕获,避免解析失败导致事件失效:self.addEventListener("push", (event) => { console.log("Push event received:", event); let notificationData = { title: "默认通知", body: "默认内容" }; try { if (event.data) { notificationData = event.data.json(); } } catch (e) { console.error("推送数据解析失败:", e); } event.waitUntil( self.registration.showNotification(notificationData.title, { body: notificationData.body, icon: "icon.png", data: { notifURL: notificationData.url || "/" } }) ); }); - 查看浏览器控制台(如Chrome的
chrome://serviceworker-internals/),确认Service Worker注册状态,是否有报错信息。
4. 测试推送与查看日志
- 使用Azure Portal的测试发送功能,选择
Web Push平台,传入符合解析格式的Payload:{ "title": "测试推送", "body": "测试内容", "url": "https://your-site.com" } - 查看Azure Notification Hub的监控日志,获取推送失败的具体原因(如无效注册ID、VAPID签名错误、权限问题等)。
5. 检查环境与浏览器限制
- 确保网站使用HTTPS(localhost开发环境除外),浏览器仅允许HTTPS下的推送功能。
- 确认浏览器通知权限已授予,且Service Worker未被浏览器终止。
内容的提问来源于stack exchange,提问作者Lama Youz
相关产品推荐
相关产品推荐

