3

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");
    };
  }
}
Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97
armanfard
  • 33
  • 4
  • Not sure what you mean here. The notification will be closed by the user or not - the window can be closed if you save the handle `var w = window.open("http://stackoverflow.com/a/13328397/1269037","_blank");` using `w.close();` unless loading a different origin blocks you from accessing the window again – mplungjan Nov 15 '16 at 09:03

1 Answers1

5

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 .

Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63
Vinay
  • 7,442
  • 6
  • 25
  • 48