1

I am wondering if there's a way to play audio when user exit my website?

for example. "thanks for visiting etc."

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
baartko
  • 97
  • 1
  • 1
  • 5

2 Answers2

8

No, you can't reliably play audio when the user leaves the website. Although you can start it (using onbeforeunload), it won't finish playing.

And seriously, if you did, it would only irritate people. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

I did a little test(still novice to the whole HTML5) and came up with this solution:

 <script>
         function myLoadHandler(evt)
        {
           var audio_file1 = document.getElementById('audioID');
            audio_file1.volume = 0
            audio_file1.play();
        }


        if ("onpagehide" in window) {
            window.addEventListener("pageshow", myLoadHandler, false);

        } else {
            window.addEventListener("load", myLoadHandler, false);
        }

    </script>

    <script>

        function playAudio() {
            var audio_file1 = document.getElementById('audioID');
            audio_file1.volume = 1
            audio_file1.play();
        }
    </script>

    <body onunload="playAudio()">
        <div>

            <div>
                <audio id="audioID" src="your_audio.wav" preload="auto"></audio>
            </div>


        </div>
    </body>

I tested it on latest Chrome and Firefox. Works only in Firefox-I guess that Chrome deletes all resources from memory quicker, than the javascript can execute.

Another weird thing is that even with preload="auto", the audio seems to actually buffer after it is played(either from script or from UI), so that's why I play it on load with volume 0.

And one more thing- like someone mentioned in the previous answer-it would probably be annoying. Use with caution.

Capaj
  • 4,024
  • 2
  • 43
  • 56