Consécutivement à l’article sur les notifications HTML 5, voici un article qui donne un exemple de fonctionnement des notifications.

La démo

Avant de pouvoir afficher une notification, vous devez autoriser le site à vous en présenter :
Il y a parfois des limitations qui empêchent le site de lancer une autorisation au chargement de la page : vous êtes parfois obligé de faire cliquer l’utilisateur sur un bouton pour voir apparaître l’avertissement d’autorisation.

Ensuite, vous pouvez afficher des notifications (avec ou sans bouton) :

Programmer une notification dans 3 secondes

Sources de l’exemple

Code HTML :

  1. <button onclick="showNotification()">Afficher la notification</button>
  2. <button onclick="p297_showNotification()">Afficher la notification</button>
  3. <a onclick="window.setTimeout(showNotification, 3000);" href="javascript:;">Programmer une notification dans 3 secondes</a>

Code javascript :

  1. <script type="text/javascript">
  2. /** Demande la permission d’afficher des notifications */
  3. function allowNotification()
  4. {
  5.   if("webkitNotifications" in window)
  6.   {
  7.     // Demande la permission. En cas de succès, afficher la notification
  8.     webkitNotifications.requestPermission(p297_showNotification);
  9.   }
  10. }
  11.  
  12. /** Affiche la notification */
  13. function showNotification()
  14. {
  15.   if("webkitNotifications" in window)
  16.   {
  17.     // Crée une notification à partir d’une image, d’un titre
  18.     // et d’une description (pas d’HTML possible).
  19.     // Pour créer une notification avec de l’HTML
  20.     // (pour le formatage), utiliser createHTMLNotification()
  21.     var notification = webkitNotifications.createNotification(
  22.       "http://www.google.fr/favicon.ico",
  23.       "Titre : cyril.me",
  24.       "Ceci est une notification"
  25.     );
  26.     // Afficher la notification
  27.     notification.show();
  28.     // N’afficher la notification que 5 secondes
  29.     window.setTimeout(function() {notification.cancel();}, 5000);
  30.   }
  31. }
  32. </script>

3 Comments

  1. droid says:

    helo cyril,

    just installed your addon 0.6 and it doesn’t seem to work for me on firefox 3.6.13

    pressing the « authorize notifications » button in your example doesn’t do anything. i don’t speak french, am i missing something you’re explaining there?

  2. Cyril says:

    Hi droid,
    Thank you for your message. You were right, there was a problem with last version. I just made a new version that will correct this problem. You can download it at mozilla addons website : https://addons.mozilla.org/fr/firefox/addon/html-notifications/

  3. droid says:

    grande, works now. thanks.