Node sw-push推送通知Action button点击无跳转 如何配置跳转链接?
Web推送通知点击跳转配置解决方案
问题原因
Web Push API本身没有原生支持click_action、url这类自动跳转的字段,这两个字段是FCM针对移动端推送的专属配置,在浏览器Web环境下不生效。所有通知交互逻辑都需要在Service Worker中手动监听处理。
第一步:调整通知 payload 结构
首先修正原代码的语法错误,同时把跳转链接统一放到data字段下方便后续读取:
const notificationPayload = JSON.stringify({ notification: { title: "Hello", body: "World", // 补全缺失的右引号 icon: "<icon link>", vibrate: [100, 50], data: { dateOfArrival: Date.now(), primaryKey: 1, defaultUrl: "https://www.google.com", // 点击通知本体的跳转地址 actions: { explore: { url: "https://www.google.com" // 对应explore按钮的跳转地址 } } }, actions: [{ action: "explore", title: "Checkout", icon: "<icon link>" }] } });
第二步:在Service Worker中添加点击事件监听
在你注册的Service Worker脚本中添加notificationclick事件处理逻辑,手动实现跳转:
self.addEventListener('notificationclick', event => { // 先关闭通知 event.notification.close(); // 读取跳转链接:优先取对应action的地址,没有就用默认地址 const action = event.action; const notificationData = event.notification.data; let targetUrl = notificationData.defaultUrl; if (action && notificationData.actions?.[action]?.url) { targetUrl = notificationData.actions[action].url; } // 执行跳转逻辑 event.waitUntil( clients.matchAll({ type: 'window', includeUncontrolled: true }) .then(windowClients => { // 检查是否已经打开了对应站点的标签页,有就直接聚焦 for (const client of windowClients) { if (client.url === targetUrl && 'focus' in client) { return client.focus(); } } // 没有就新开标签页 if (clients.openWindow) { return clients.openWindow(targetUrl); } }) ); });
注意事项
- 跳转的目标域名必须和Service Worker的注册域名同域,否则会被浏览器安全策略拦截
- 修改Service Worker代码后,需要重新激活Service Worker才能生效,避免浏览器加载旧的缓存脚本
内容的提问来源于stack exchange,提问作者Pratik Agarwal
相关产品推荐
相关产品推荐

