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

如何从Web推送通知负载中提取数据?附接收的负载示例

如何从Web推送通知负载中提取数据

嘿,我来帮你搞定这个Web推送负载的数据提取问题!你给出的负载里有个关键细节需要注意:data字段下的notification是一个JSON字符串,不是直接可用的JavaScript对象,所以得先解析它才能拿到里面的内容。下面是具体步骤和代码示例:

1. 获取推送负载(在Service Worker中处理)

通常我们会在Service Worker的push事件里接收推送负载,先把它转成JSON对象:

self.addEventListener('push', (event) => {
  // 先判断是否有负载数据,再转成JSON
  const payload = event.data ? event.data.json() : {};
  // 此时payload就是你提供的包含data字段的对象
});

2. 解析notification字段的JSON字符串

因为payload.data.notification是字符串格式的JSON,必须用JSON.parse()把它转成可操作的对象。为了避免格式错误导致崩溃,建议用try-catch包裹:

let notificationData;
try {
  // 解析JSON字符串
  notificationData = JSON.parse(payload.data.notification);
} catch (error) {
  console.error('解析notification字段失败:', error);
  // 解析失败可以在这里做降级处理,比如用默认值
  return;
}

3. 提取具体数据字段

现在notificationData已经是普通的JavaScript对象了,你可以直接访问里面的任意字段:

// 提取基础通知内容
const notificationTitle = notificationData.title; // 结果:"HELLO"
const notificationBody = notificationData.body; // 结果:"12:30"
const notificationIcon = notificationData.icon; // 结果:"/static/assets/notifications/loader-100x100.png"

// 提取震动模式
const vibratePattern = notificationData.vibrate; // 结果:[200,100,200,100,200,100,400]

// 提取操作按钮列表
const actionButtons = notificationData.actions;
// 比如获取第一个按钮的跳转链接
const firstActionUrl = actionButtons[0].action; // 结果:"https://example.com/#done"

额外注意事项

  • 如果你不确定某些字段是否存在,可以用可选链操作符?.来避免报错,比如const title = notificationData?.title || '默认标题';
  • 确保推送方发送的notification字段是标准的JSON格式,否则解析会失败,这时候try-catch里的错误处理就很重要了

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:35:24