0

I have a website (gitter.im) that use notifications and I want to run sound when notifications are pushed. How can I add this code to notification?

(function() {
    var a = document.createElement('audio')
    a.setAttribute('autoplay', true)
    a.setAttribute('src', 'http://www.soundjay.com/button/beep-03.mp3')
})();
jcubic
  • 61,973
  • 54
  • 229
  • 402

2 Answers2

2

You can use HTML5 audio api, but it doesn't work in service worker.

The only way to make a sound when browser receive notification is via postMessage(), you can notify your web page to make a sound, but it will work only if main site page is open in a browser.

(Chrome ServiceWorker postMessage)

var track = new Audio("http://oringz.com/oringz-uploads/sounds-874-gets-in-the-way.mp3");
track.play();

More information: http://www.html5rocks.com/en/tutorials/webaudio/intro/

Community
  • 1
  • 1
  • I know how to play sound but how I can add sound to gitter.im that I don't have control of? – jcubic Mar 15 '16 at 12:09
  • So you are talking about simple browser notifications, not about push notifications with service workers, yes? Push notifications allows you push notification even if your website isn't opened currently, it works in chrome, safari and firefox, but api is different. About chrome push notifications: https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web?hl=en – Juris Pukitis Mar 16 '16 at 09:44
  • I don't close gitter tab so I don't know if they are push notifications in service worker or normal notifications. – jcubic Mar 16 '16 at 10:19
0

This seems to work:

(function(Notif) {
  function play() {
    var a = document.createElement('audio')
    a.setAttribute('autoplay', true)
    a.setAttribute('src', 'http://www.soundjay.com/button/beep-03.mp3');
  }
  window.Notification = function(title, option) {
    var notif = new Notif(title, option);
    play();
    return notif;
  };
  for (var key in Notif) {
    if (Notif.hasOwnProperty(key)) {
      window.Notification[key] = Notif[key];
    }
  }
})(Notification);
jcubic
  • 61,973
  • 54
  • 229
  • 402