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

可紊 提交于 2020-01-21 12:27:26

问题


This is my code to show notification in Google Chrome.

How can I close notification in code?

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");
    };
  }
}

回答1:


It's simple, every notification object has close() method you need to just push them on to an array and call close() on each one of them before window 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; 

You can also associate removeAllNotifys() on some button click to clear all notification or use setTimeout to remove them say after 2 seconds .



来源:https://stackoverflow.com/questions/40605653/how-can-remove-all-chrome-notifications-in-load-view-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!