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

问题描述:

我有一个使用通知的网站(gitter.im),我希望在推送通知时运行声音。我如何将此代码添加到通知?如何在第三方网站上推送html5通知时执行代码

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

这似乎工作:

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

您可以使用HTML5音频API,但它不能在服务人员的工作。

浏览器收到通知时发出声音的唯一方法是通过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/

+0

我知道怎么打声除H我可以给gitter.im添加声音,但我没有控制权? – jcubic

+0

所以你说的是简单的浏览器通知,而不是与服务人员推送通知,是吗? 推送通知允许您推送通知,即使您的网站目前没有打开,它可以在Chrome浏览器,safari和firefox中运行,但api不同。 关于Chrome推送通知: https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web?hl=zh-CN –

+0

我不关闭gitter选项卡我不知道他们是否是服务人员推送通知或正常通知。 – jcubic