Reliably Dismissing Webkit Notifications

2019-05-09 04:59发布

问题:

I'm successfully creating and dismissing webkit notifications like so:

notification = window.webkitNotifications.createNotification('foo.png', 'bar', 'baz')
notification.show()
setTimeout ->
    notification.cancel()
, 3000

However, the notifications aren't dismissed if the user closes or refreshes the page during those three seconds, and they stay on the desktop until manually closed.

Is there a way to reliably dismiss them under these circumstances?

回答1:

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.