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

使用Web Push发送ArrayBuffer时service worker端event.data为null如何解决

Web Push推送二进制数据时event.data为null的解决方案

核心原因

浏览器虽然收到了推送事件,但无法正确解密服务端发送的加密payload,最终将data字段置为null,常见触发场景和修复方法如下:

1. 加密编码不兼容

web-push库默认的加密编码可能和浏览器支持的标准不匹配,需要显式指定通用的aes128gcm编码:

// Node.js侧修改发送代码
webpush.sendNotification(subscription, buffer, {
  contentEncoding: 'aes128gcm'
})

2. 订阅参数配置错误

前端订阅推送时必须配置正确的VAPID公钥,且确保公钥已经转换为Uint8Array格式,缺少正确密钥的情况下浏览器无法解密payload:

// 前端订阅示例
const publicKey = '你的VAPID公钥字符串';
// 公钥转换方法
function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = window.atob(base64);
  return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
}

const subscription = await registration.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: urlBase64ToUint8Array(publicKey)
})

3. 运行环境不符合要求

Web Push的payload解密仅支持HTTPS环境(仅localhost本地开发可豁免),部署在非HTTPS环境下会出现收到推送但payload为null的问题。

4. payload超出大小限制

主流浏览器对Web Push的payload大小限制为4KB,超出限制的内容会被浏览器直接丢弃,需控制发送的二进制数据大小不超过该阈值。

Service Worker侧获取二进制数据示例

修复上述问题后,可通过如下方式获取ArrayBuffer:

self.addEventListener('push', function (event) {
  if (event.data) {
    const binaryData = event.data.arrayBuffer();
    // 后续处理逻辑
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:24:00