我们要实现这样一个场景用户访问我的页面之后将页面放在了后台可能切换到了别的窗口或应用此时有新的消息想给用户提示。实现效果先说说实现的逻辑1.弹窗询问用户是否授权通知这里我们可以拿到三种状态的权限允许(granted)、询问(default)、屏蔽(denied)2.如果用户不选择/不允许后续就无需系统通知3.如果用户允许后续将进行系统通知注意这里我们需要注意两种特殊情况通知不会弹出1.开发环境是 http://192.36.68... 类似的域名但 http://localhost... 可以但可能会被浏览器默认屏蔽因此最好是在 https 环境下进行测试2.Windows系统的专注助手可能会被设置“优先通知”/“仅显示闹钟”专注助手在设置-系统-专注助手这里可以设置成“关”或特殊设置“仅优先通知”代码实现const judgePower () { // 判断后台通知权限是否开启 console.log(judgePower, Notification.permission) if (Notification.permission default) { Notification.requestPermission().then(permission { if (permission granted) { console.log(操作设置为 allow) notifyPolling() } else if (permission denied) { alert(如需后台消息提示请在浏览器地址栏开启通知权限) } }) } if (Notification.permission granted) { console.log(用户已允许通知) notifyPolling() } } const notifyInfo () { if (Notification.permission ! granted) return new Notification(系统通知, { body: 有新消息请查看, icon: // 设置icon图标存放地址 }) } let notifyTimer null const notifyPolling () { // 轮询有无新消息 if (notifyTimer) return notifyTimer setInterval(async () { notifyInfo() }, 60000) } onMounted(() { judgePower() })如果需要添加接口调用等可以在 notifyPolling 方法中进行。值得注意的是我们如果想点击通知就可以激活当前放在后台的页面可以这样做const notifyInfo () { if (Notification.permission ! granted) return const notification new Notification(系统通知, { body: 有新消息请查看, icon: }) notification.onclick () { window.focus() notification.close() } }此时我们点击通知就可以打开已经激活的页面如果想跳转到其他的页面可以借助notification.onclick () { window.focus() notification.close() router.push(url) } // OR notification.onclick () { window.focus() notification.close() window.location.href url }如果跳转的路由拼接了参数并且和原先页面的路由仅有参数的区别可能会不触发页面的更新记得添加路由的监听比如watch( () route.query.id, (id) { if (!id) return // ...你的逻辑 }, { immediate: true } )当然如果不想破坏用户正在进行的操作我们最好给用户新增一个标签页notification.onclick () { window.focus() notification.close() setTimeout(() { window.open(url, _blank) }, 0) }