armanfard
armanfard

Reputation: 33

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

Upvotes: 3

Views: 2600

Answers (1)

Vinay
Vinay

Reputation: 7674

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 .

Upvotes: 5

Related Questions