React+Node.js推送通知显示[object Object]问题求助
问题分析与修复
你遇到的通知显示[object Object]的核心原因是调用showNotification的参数格式错误。
showNotification的正确语法是:
self.registration.showNotification(title, options);
第一个参数是字符串类型的通知标题,第二个参数是配置对象(包含body、data等选项)。但你现在把标题和选项都塞进了第一个参数的对象里,导致浏览器把这个对象直接转成字符串[object Object]作为标题显示。
修复后的Service Worker代码
self.addEventListener('push', async (event) => { const { type, title, body, data: { redirectUrl }, } = event.data.json() if (type === 'NEW_MESSAGE') { try { event.waitUntil( self.clients.matchAll().then((clients) => { const filteredClients = clients.filter((client) => client.url.includes(redirectUrl)) if ( filteredClients.length === 0 || (filteredClients.length > 0 && filteredClients.every((client) => client.visibilityState === 'hidden')) ) { // 修正showNotification的参数格式 self.registration.showNotification(title, { body, // 把redirectUrl存入notification的data,方便点击跳转时使用 data: { redirectUrl } }) } }), ) } catch (error) { console.error('Error while fetching clients:', error.message) } } }) self.addEventListener('notificationclick', (event) => { event.notification.close() // 原逻辑中event.action不会等于'NEW_MESSAGE',因为未配置actions选项 event.waitUntil( self.clients.matchAll().then((clients) => { const redirectUrl = event.notification.data.redirectUrl // 优先聚焦已打开的对应窗口,否则打开新窗口 const targetClient = clients.find(client => client.url.includes(redirectUrl)) if (targetClient) { targetClient.focus() } else { self.clients.openWindow(redirectUrl).then(client => client?.focus()) } }) ) })
额外说明
- 原
notificationclick事件里的event.action === 'NEW_MESSAGE'逻辑无效,因为你没有在通知配置里设置actions选项,点击通知时event.action会是undefined,直接通过notification.data获取跳转地址即可。 - 修复后通知会正确显示
title作为标题、body作为内容,同时redirectUrl被存入通知的data中,点击时可以正常跳转或聚焦对应窗口。
内容的提问来源于stack exchange,提问作者fatih.jsx
相关产品推荐
相关产品推荐

