Chrome推送通知showNotification方法报错,寻求问题排查方案
ServiceWorker通知showNotification报错排查
错误信息
在 'ServiceWorkerRegistration' 上执行 'showNotification' 失败:无法从 'NotificationOptions' 读取 'actions' 属性:无法从 'NotificationAction' 读取 'action' 属性:必填成员未定义
我的代码
if (event.data) { console.log('notifications will be displayed here'); try { const message = await event.data.json(); console.log({message}); let {title, description, image} = message; console.log({message}); const options = { body: 'This is the body of the notification.', icon: '', actions: [ {action: 'action-1', title: 'Action 1'}, {action: 'action-2', title: 'Action 2'}, ], }; await event.waitUntil(self.registration.showNotification(title, options)); } catch (error) { console.error('error in notification', error); } } else { console.error('notification has no message'); } });
问题定位与解决建议
从错误提示来看,核心问题是传递给showNotification的actions数组中,某个NotificationAction对象缺少必填的action字段,但从贴出的代码看,两个action对象都明确定义了action和title,可以从以下几个方向排查:
- 检查字段拼写与运行时值:确认代码执行时
options.actions里的每个对象确实存在action字段,排查是否有其他异步操作或变量污染意外修改了这个数组。 - 修正
event.waitUntil用法:event.waitUntil接受Promise作为参数,不需要用await修饰,正确写法应为:
多余的event.waitUntil(self.registration.showNotification(title, options));await会导致传递给event.waitUntil的是undefined,虽不是当前错误的直接原因,但会引发其他潜在问题。 - 确保
title参数有效:如果message中没有title字段,会导致title为undefined,部分浏览器可能出现异常联动,建议给title设置默认值:let {title = '默认通知标题', description, image} = message; - 环境与兼容性检查:确保运行环境为HTTPS(localhost开发除外),同时检查浏览器版本,部分旧版本浏览器对Notification Actions支持有限,可先移除
actions参数测试是否能正常显示通知,以此排除特性兼容性问题。
内容的提问来源于stack exchange,提问作者JIMMY JACOB
相关产品推荐
相关产品推荐

