按标签名称隐藏 JS 通知对象



我正在为我的项目使用通知 API 来显示浏览器通知,其中每个通知都有一个唯一的标签 (ID),但我似乎找不到一种方法来关闭或隐藏标签名称的通知,而不调用对象的 close 函数,因为它可能会被其他页面关闭而不是它的来源。这种事情可能吗?

您可以将通知保存在 localStorage 中,然后检索并关闭它。

例如

// on create
var n = new Notification('Notification Title', {
        tag: _this.attr('data-notification-id')
    });
window.localStorage.setItem('data-notification-id', n);

// then later
var n = window.localStorage.getItem('data-notification-id');
n.close();

我现在已经解决了这个问题,但我的解决方案似乎很奇怪,所以我仍然接受其他遵循更"正常"方法的答案。

基本上,使用标记创建的新通知对象,而当前已可见的通知已经具有相同的标记,则删除原始通知。因此,通过创建一个具有相同标签的新通知对象并立即将其删除,我可以"删除"旧通知。

用于查看通知的链接

<a href="/some/url" data-notification-id="1234">View this notification</a>

而 jQuery

$('a[data-notification-id]').on('click', function(){
    var _this = $(this);
    var n = new Notification('Notification Title', {
        tag: _this.attr('data-notification-id')
    });
    setTimeout(n.close.bind(n), 0);
});

您可以将通知选项字符串化,并使用标记作为存储密钥保存到会话(或本地)存储。然后,您可以使用存储的通知选项重新创建/替换它,然后调用close。

创建通知:

if (("Notification" in window)) {
   if (Notification.permission === "granted") {
      var options = {
         body: sBody,
         icon: sIcon,
         title: sTitle, //used for re-create/close 
         requireInteraction: true,
         tag: sTag
      }
      var n = new Notification(sTitle, options);
      n.addEventListener("click", function (event) {
         this.close();
         sessionStorage.removeItem('notification-' + sTag);
      }, false);
      sessionStorage.setItem('notification-' + sTag, JSON.stringify(options));
   }
}

清除通知:

function notificationClear(sTag) {
    var options = JSON.parse(sessionStorage.getItem('notification-' + sTag));
    if (options) {
        options.requireInteraction = false;
        if (("Notification" in window)) {
            if (Notification.permission === "granted") {
                var n = new Notification(options.title, options);
                setTimeout(function () {
                    n.close();
                    sessionStorage.removeItem('notification-' + sTag);
                }, 500); //can't close it immediately, so setTimeout is used
            }
        }
    }       
}

最新更新