网页刷新后如何保留Notification点击事件?
持久化浏览器通知实现及注意事项
我来分享一段实现持久化浏览器通知的代码,不过要注意它存在一个小问题:
function sendNotification (title = 'Hi') { var a = new Notification(title, { requireInteraction: true, renotify: true, tag: 123, }) a.onclick = function () { // Click event will lose after refresh console.log('get') } } if (!("Notification" in window)) { alert("not support"); } else if (Notification.permission === "granted") { // If it's okay let's create a notification sendNotification() } else if (Notification.permission !== 'denied') { Notification.requestPermission() .then( permission => { if (permission === "granted") { sendNotification() } } ) }
代码说明
- 这段代码会创建一个不会自动消失的浏览器通知(通过
requireInteraction: true实现) - 点击通知时,控制台会打印
get - 但要注意:当页面刷新后,通知的点击事件绑定以及变量
a都会丢失——因为页面刷新会重置所有内存中的变量和事件监听
测试提示
代码里已经处理了通知权限的判断和申请逻辑,你可以直接把这段代码复制到浏览器控制台进行调试。
内容的提问来源于stack exchange,提问作者Dark Flame Master
相关产品推荐
相关产品推荐

