You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网页刷新后如何保留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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:32:46