这是我在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");
};
}
}
答案 0 :(得分:4)
很简单,每个通知对象都有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;
您还可以在某个按钮上关联removeAllNotifys()
以清除所有通知,或者使用setTimeout在2秒后删除它们。