如何用JavaScript在加载视图中删除所有Chrome通知

How can remove all Chrome notifications in load view with JavaScript?

本文关键字:删除 Chrome 通知 视图 何用 JavaScript 加载      更新时间:2023-09-26

这是我在Google Chrome中显示通知的代码。

如何在代码中关闭通知?

document.addEventListener('DOMContentLoaded', function() {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.');
    return;
  }
  if (Notification.permission !== "granted")
    Notification.requestPermission();
});
function notifyMe() {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
    var notification = new Notification('test', {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "test",
    });
    notification.onclick = function() {
      window.open("http://stackoverflow.com/a/13328397/1269037");
    };
  }
}

这很简单,每个通知对象都有close()方法,你只需要将它们推送到一个数组中,并在窗口关闭前对每个通知对象调用close()

var notify=[];
for(var i=0; i<=4;i++){
  var notification = new Notification('test', {
  icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
  body: "test"+i
  });                                  //create some notifications
  notify.push(notification);
}
function removeAllNotifys()
{
  for(var i=0; i<notify.length;i++){
    notify[i].close();                 //remove them all  
  }
}
window.onbeforeunload = removeAllNotifys; 

你也可以在一些按钮上关联removeAllNotifys()点击清除所有通知或使用setTimeout来删除它们说2秒后。