首页 > 解决方案 > 检查 JavaScript 中是否存在通知

问题描述

铬浏览器。

每次刷新页面时都会执行该脚本。

是否可以验证通知的存在以免重复。

if ($('.snippet__title').length) {
  var titles = document.querySelectorAll('.snippet__title')
  titles.forEach((title) => {
    if (title.textContent.includes('searchString')) {
      var msg = title.textContent.trim()
      var notification = new Notification('Element found', {
        body: msg,
        dir: 'auto',
        icon: 'icon.jpg'
      });
    }
  })
}

标签: javascriptnotifications

解决方案


谢谢mplungjan。所以我想这样做,但我认为仍然有一些解决方案。

使用 localStorage 的工作解决方案

    var NotifyShowed = localStorage.getItem('NotifyShowed')

    if (!NotifyShowed) {
        if ($('.snippet__title').length) {
          var titles = document.querySelectorAll('.snippet__title')
          titles.forEach((title) => {
            if (title.textContent.includes('searchString')) {
              var msg = title.textContent.trim()
              var notification = new Notification('Element found', {
                body: msg,
                dir: 'auto',
                icon: 'icon.jpg'
              });
              localStorage.setItem('NotifyShowed', true);
            }
          })
        }
    }

推荐阅读