问题描述
我正在使用标准处理我的Web应用程序的桌面通知。
出于初步开发的目的,我使用的是谷歌浏览器。
使用Chrome,当页面创建Notification
对象时,通知将永久保留在桌面上。
Notification
原型确实有一个.close()
方法,该方法允许关闭先前调用过的通知。
我想这个,结合setTimeout
函数会在几秒钟之后自动解除通知。
我甚至找到我的想法 。
但是,似乎我无法使用setTimeout
函数使通知的范围正常工作,并且不会为每个创建的通知正确.close()
方法。
这是我尝试过的(我在使用了一些代码作为起点):
按钮:
<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>
如果有经验的人能帮助我,我将不胜感激。
1楼
当我将它包装到一个function() {}
它工作:
setTimeout(function() { notification.close() }, 2000);
看到这个小提琴: :