gpt4 book ai didi

javascript - 隐藏以前的 HTML 桌面通知

转载 作者:可可西里 更新时间:2023-11-01 14:54:38 24 4
gpt4 key购买 nike

我目前正在使用以下代码为我的控制台生成 HTML5 桌面通知。

<script type="text/javascript">
$(document).ready(function() {
$('#show_button').click(function(e) {
e.preventDefault();
window.webkitNotifications.requestPermission();
});
if (window.webkitNotifications.checkPermission() == 0) {
notification = window.webkitNotifications.createNotification('favicon.ico', 'New orders!', 'You have new orders.');
notification.show();
setTimeout(function() {
notification.cancel();
}, '5000');
}
});
</script>

通知会在 5 秒后再次出现并消失,但是如果我在 5 秒之前单击新页面或关闭窗口,则通知不会关闭。由于页面设置为每 5 分钟刷新一次,这会导致出现许多通知,然后需要手动关闭每一个通知。

是否有一种方法可以在 Javascript 中检查是否有任何先前的通知在后面等待并关闭它们,或者确保即使窗口关闭通知也会消失?

最佳答案

根据:Reliably Dismissing Webkit Notifications

Use a window.onunload or window.onbeforeunload handler to clear the noifications when the page is closed. This does not preserve the three-second delay, however, since notifications will be closed immediately when the page closes.

Another option (that does preserve the three-second delay) is to create the notifications from HTML pages using createHTMLNotification(url). Have the notification page close itself by including a script like setTimeout(window.close, 3000) within the notification HTML document. In this case, obviously, you don't need a setTimeout call in your main page, since it is already included in the notification.

此代码有效:但是,在 Chrome 上,它仅在更改或关闭页面时有效,似乎在刷新时无效。这是 Chromium wiki 中记录的错误所以我想这很快就会得到解决......

$(window).on('beforeunload', function() {
notification.cancel();
});

关于javascript - 隐藏以前的 HTML 桌面通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com