Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
    };
  }
}
like image 317
armanfard Avatar asked Jul 26 '26 16:07

armanfard


1 Answers

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 .

like image 56
Vinay Avatar answered Jul 28 '26 14:07

Vinay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!