Angular中SwPush.notificationClicks无法接收数据对象问题排查
Angular SwPush notificationClicks无法获取data对象的解决方案
在Angular项目中使用SwPush实现推送通知时,SwPush.messages能正常接收包含根级data的推送内容,但SwPush.notificationClicks回调中的notification.data始终为null,即使自定义Service Worker也无法解决。
问题原因
这是因为FCM(或Azure Notification Hubs)推送的消息结构中,根级data字段不会自动挂载到Notification API的notification.data属性中。Angular的SwPush依赖标准Notification API,默认只会读取notification字段内部的data。
解决方案
方案1:调整推送消息结构
将自定义data嵌入到推送消息的notification字段内部,而非根级。这样SwPush的notificationClicks就能直接获取到data。
示例推送结构:
{ "notification": { "title": "Notification Hub Test Notification", "body": "This is a sample notification delivered by Azure Notification Hubs.", "data": { "property2": "42", "property1": "value1" } }, "from": "55851556555", "priority": "normal", "fcmMessageId": "ID" }
方案2:自定义Service Worker手动传递data
如果无法修改推送消息结构,需要在自定义Service Worker中,在接收推送时将根级data附加到Notification配置中,并在点击事件中传递给Angular应用。
步骤1:编写自定义Service Worker代码
self.addEventListener('push', (event) => { const payload = event.data?.json() || {}; const notificationOptions = { title: payload.notification.title, body: payload.notification.body, // 将根级data赋值给notification的data属性 data: payload.data || {} }; event.waitUntil( self.registration.showNotification(payload.notification.title, notificationOptions) ); }); self.addEventListener('notificationclick', (event) => { event.notification.close(); const clickData = event.notification.data; // 将data发送给Angular应用 event.waitUntil( self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => { clients.forEach(client => { client.postMessage({ type: 'NOTIFICATION_CLICK', payload: clickData }); }); }) ); });
步骤2:在Angular应用中监听Service Worker消息
在组件或服务中添加监听逻辑:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-notification-handler', templateUrl: './notification-handler.component.html' }) export class NotificationHandlerComponent implements OnInit { ngOnInit(): void { if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', (event) => { if (event.data.type === 'NOTIFICATION_CLICK') { console.log('通知点击携带的数据:', event.data.payload); // 在此处理业务逻辑 } }); } } }
注意事项
- 确保Angular正确注册自定义Service Worker,在
angular.json中配置serviceWorker: true并指定自定义SW路径。 - 之前自定义SW无效的核心原因是未在
push事件中将根级data传递给showNotification的配置项,导致Notification对象的data始终为空。
内容的提问来源于stack exchange,提问作者Giorgi Mamisashvili
相关产品推荐
相关产品推荐

