点了通知只能跳首页,这次终于可以让浏览器自己决定去哪了
Firefox 158 Beta(2026-09-28)正式支持 Notification constructor 和 ServiceWorkerRegistration.showNotification() 的 navigate 选项——点击通知后浏览器直接跳到指定 URL,不再需要 JS 中转。
旧做法:多一步 fetch,多一堆风险
在 navigate 选项出现之前,点击 Web 通知后跳转到指定页面的标准做法是监听 notificationclick 事件,然后在事件处理器里手动 clients.openWindow():
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(
clients.openWindow('https://example.com/order/12345')
);
});
这看起来简单,但有三个实际问题:
- Service Worker 冷启动延迟:如果 SW 还没被激活,点了通知要先等 SW 启动,再执行
openWindow,用户会感觉”点了没反应” - Focus 逻辑要自己写:多个窗口的情况下,
openWindow可能开新标签而不是聚焦已有标签,还要额外写clients.matchAll()判断要不要聚焦 - 测试复杂度高:notificationclick 事件在后台触发,本地调试断点不好打,只能靠日志
新做法:告诉浏览器,剩下的它自己搞定
navigate 选项把这个流程直接下放给浏览器内核:
// 旧写法(SW notificationclick 监听器)
new Notification('订单已发货', {
body: '点击查看物流详情',
data: { url: '/order/12345' }
});
// SW 里还要写 notificationclick 处理器
// 新写法(navigate 选项,Firefox 158+)
new Notification('订单已发货', {
body: '点击查看物流详情',
navigate: '/order/12345' // 浏览器自动处理跳转
});
浏览器收到 navigate 参数后,点击通知直接跳转,无需 SW 介入。对于已经激活的 SW 场景,showNotification 也支持同一参数:
registration.showNotification('新消息', {
body: '张三给你发了一条消息',
navigate: '/messages/789',
tag: 'msg-789'
});
与现有做法的关系:不是替换,是降级
navigate 选项和原有的 notificationclick + clients.openWindow() 是共存关系,不是替代:
// 如果你的 SW 已经有 notificationclick 处理器,浏览器优先执行它
// navigate 只在 SW 没有处理该通知时生效
self.addEventListener('notificationclick', (event) => {
// 你的自定义逻辑仍然运行
event.waitUntil(
analytics.track('notification_clicked', event.notification.data)
.then(() => clients.openWindow(event.notification.data.url))
);
});
这个设计让渐进增强成为可能:老浏览器忽略 navigate 参数,走原有 notificationclick 路径;Firefox 158+ 如果发现 SW 没有处理该通知,就直接用 navigate 跳转。
一个真实场景的对比
订单通知场景:
// 旧:SW 拦截,手动跳转
registration.showNotification('您的订单已发货', {
body: '顺丰单号 SF123456789',
data: { orderId: '12345' }
});
// SW notificationclick 里还要判断 tag,避免重复弹窗
// 新:声明式跳转,SW 可以专注做分析
registration.showNotification('您的订单已发货', {
body: '顺丰单号 SF123456789',
tag: 'order-shipped-12345',
navigate: `/orders/12345?from=notification`
});
// SW 的 notificationclick 只做数据分析,不做页面跳转
浏览器支持
| 浏览器 | 支持状态 |
|---|---|
| Firefox | 158 Beta+(2026-09-28),Stable 预计 11 月 |
| Chrome | 未确认(Notification API 本身 Chrome 140+ 支持,但 navigate 选项需查 spec) |
| Safari | 未支持 |
规范原文在 MDN Notification constructor navigate。
下一步
如果你现在已经在 SW 的 notificationclick 里做了页面跳转,可以考虑把 navigate 选项作为第一方案——浏览器内核执行跳转比 SW clients.openWindow() 更稳定、更快(无冷启动延迟)。保留 notificationclick 里的分析逻辑,只把跳转职责剥离出来。
对于没有 SW 的简单场景(比如主线程直接 new Notification),navigate 选项让整个流程不再需要 SW,测试成本大幅降低。
评论区
登录后可评论。