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

arm*_*ard 3 javascript notifications google-chrome

这是我在 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");
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

Vin*_*ney 5

很简单,每个通知对象都有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; 
Run Code Online (Sandbox Code Playgroud)

您还可以关联removeAllNotifys()某些按钮单击以清除所有通知或使用 setTimeout 在 2 秒后删除它们。