3

I'm currently using the following code to generate HTML5 desktop notifications for my console.

<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>

The notifications appear and disappear again after 5 seconds, however if I click onto a new page or close the window before the 5 seconds are up, then the notification doesn't close. Since the page is set to refresh every 5 minutes, this can result in many notifications appearing, and each of these then need to be closed manually.

Is there a method to check in Javascript if there are any previous notifications waiting behind and close them, or to make sure a notification goes away even if the window is closed?

rds
  • 26,253
  • 19
  • 107
  • 134
Toby
  • 1,651
  • 2
  • 18
  • 31

1 Answers1

1

As per: 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.

This code works: However, on Chrome, it only works when changing or closing a page, it doesnt seem to work on refresh. It's a recorded bug in the Chromium wiki so i assume this will get fixed soon...

$(window).on('beforeunload', function() {
  notification.cancel();
});
Community
  • 1
  • 1
Toby
  • 1,651
  • 2
  • 18
  • 31
  • createHTMLNotification was removed from the html5 spec and from Chrome: https://plus.google.com/u/0/+GoogleChromeDevelopers/posts/8vWo8hq4pDm – nothingisnecessary Mar 21 '13 at 19:54
  • Only html notifications are being deprecated, usual notifications (e.g. The ones used in gmail) will still work – Toby Mar 21 '13 at 22:59