Autoplay sound in chrome background tab

前端 未结 3 757
醉梦人生
醉梦人生 2021-02-13 12:41

I have an HTML5 game that uses audio notifications.

When users are searching for other players with match-making they frequently change tabs to do other things and rely

3条回答
  •  眼角桃花
    2021-02-13 13:18

    Here, background tabs still can play sounds from elements (Chrome 49.0.2623.87). However, if Chrome blocked this, a way to work around it would be to notify the front tab of an event and have it play the sound instead of the background tab.

    The following would need to be implemented as a userscript extension so that it could work on any tab - as a demo, it works just between two tabs with the same JSBin URL:

    var intercom = Intercom.getInstance();
    
    document.addEventListener("visibilitychange", getVisible);
    
    function getVisible (evt) {
      document.getElementById("fg-indicate").style.visibility = document.visibilityState;
      if (document.visibilityState == "visible") {    
         // tab comes to front => listen to intercom
         intercom.on('notice', play);
       } else {
         // kill callback
         intercom.off('notice', play);
         // call intercom with delay
         window.setTimeout(function f() {
           intercom.emit('notice', {message: 'Hello, all windows!'});
         }, 3000);
       }
    }
    
    function play() {
      document.getElementsByTagName("audio")[0].play();
    }
    

    It relies on the intercom.js library and uses localstorage to communicate between open tabs.

    Try this out by

    • opening https://jsbin.com/gerihijofe/1/edit?html,js,output in one tab
    • then in another tab
    • switch tabs
    • wait for 3s, see where the little speaker icon appears
    • switch tabs
    • wait for 3s, see where the little speaker icon appears

    and so on.

    The code and a bit more code to inject an element could be wrapped in a userscript so it can run on any site that happens to be in front.

提交回复
热议问题