0

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

4

3 回答 3

2

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

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

查看通知的链接

<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);
});
于 2015-06-18T16:22:35.737 回答
2

您可以将通知保存在 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();
于 2015-06-23T11:27:49.407 回答
0

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

创建通知:

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
            }
        }
    }       
}
于 2020-12-04T02:16:45.693 回答