如何在第三方站点上推送 html5 通知时执行代码

How to execute code when html5 notification is pushed on 3rd party site

本文关键字:通知 html5 执行 代码 上推 第三方 站点      更新时间:2023-09-26

我有一个使用通知的网站(gitter.im),我想在推送通知时运行声音。如何将此代码添加到通知中?

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

您可以使用 HTML5 音频 api,但它在 service worker 中不起作用。

当浏览器收到通知时发出声音的唯一方法是通过postMessage(),您可以通知网页发出声音,但只有在浏览器中打开主站点页面时,它才会起作用。

(Chrome ServiceWorker postMessage)

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

更多信息:http://www.html5rocks.com/en/tutorials/webaudio/intro/

似乎有效:

(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);