如何正确设置浏览器创建的桌面通知的关闭超时
How do I properly set a close timeout on desktop notifications created by the browser
我正在使用标准 Notification API 为我的 Web 应用程序处理桌面通知。出于初始开发的目的,我使用 Google Chrome。使用 Chrome,当页面创建 Notification
对象时,通知将永远保留在桌面上。
Notification
原型确实有一个 .close()
方法,它允许关闭之前调用的通知。我认为这与 setTimeout
功能结合使用会在几秒钟后自动关闭通知,这是小菜一碟。我什至找到了 a guide confirming 我的想法。
但是,我似乎无法使通知的范围与 setTimeout
函数一起正常工作,并且没有为每个创建的通知正确调用 .close()
方法。
这是我尝试过的方法(我使用了 another answer 中的一些代码作为起点):
按钮:
<button onclick="notifyMe()">
Notify me!
</button>
JavaScript:
<script>
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
//alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification');
notification.onclick = function () {
window.focus();
};
setTimeout(notification.close, 2000);
// Result: Uncaught TypeError: Illegal invocation
// also tried.....
// setTimeout(notification.close(), 2000);
// Result: notification stays open forever
// setTimeout('notification.close', 2000);
// Result: ReferenceError: notification is not defined
}
}
</script>
如果有这方面经验的人能帮助我,我将不胜感激。
当我将它包装成 function() {}
时,它起作用了:
setTimeout(function() { notification.close() }, 2000);
看到这个fiddle:https://jsfiddle.net/drnz12n8/2/
我正在使用标准 Notification API 为我的 Web 应用程序处理桌面通知。出于初始开发的目的,我使用 Google Chrome。使用 Chrome,当页面创建 Notification
对象时,通知将永远保留在桌面上。
Notification
原型确实有一个 .close()
方法,它允许关闭之前调用的通知。我认为这与 setTimeout
功能结合使用会在几秒钟后自动关闭通知,这是小菜一碟。我什至找到了 a guide confirming 我的想法。
但是,我似乎无法使通知的范围与 setTimeout
函数一起正常工作,并且没有为每个创建的通知正确调用 .close()
方法。
这是我尝试过的方法(我使用了 another answer 中的一些代码作为起点):
按钮:
<button onclick="notifyMe()">
Notify me!
</button>
JavaScript:
<script>
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
//alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification');
notification.onclick = function () {
window.focus();
};
setTimeout(notification.close, 2000);
// Result: Uncaught TypeError: Illegal invocation
// also tried.....
// setTimeout(notification.close(), 2000);
// Result: notification stays open forever
// setTimeout('notification.close', 2000);
// Result: ReferenceError: notification is not defined
}
}
</script>
如果有这方面经验的人能帮助我,我将不胜感激。
当我将它包装成 function() {}
时,它起作用了:
setTimeout(function() { notification.close() }, 2000);
看到这个fiddle:https://jsfiddle.net/drnz12n8/2/