Before you relink me, I've read questions like How do I stop a page from unloading (navigating away) in JS?, but they deal with HTML4 and below. I want an answer that utilizes the HTML5 event attribute onunload
. I also want this to be as pure as possible, that is without external libraries or plugins like jQuery or Flash and only using standardized code (PURE HTML, CSS, and JavaScript, nothing platform-dependant).
Before you tell me to use onbeforeunload
, note that it is NON-STANDARD, and therefore does not fit my criteria as described above. It does NOT work on all browsers, especially those made before IE implemented it.
Question
On my site, I have several music players, and if any one of them is playing when the user attempts to navigate away from the page, I want to popup a dialog box ensuring that they intended this and that they understand that this will stop the audio stream, and if they choose "yes" or "OK", it proceeds with the navigation, but if they click "no" or "Cancel", it stays on the same page and keeps playing the audio without a break. How do I use JavaScript to cancel the page unloading WITHOUT USING ONBEFOREUNLOAD
?
Code so far
I have the following code so far, but no idea how to stop unloading:
<!DOCTYPE HTML><html>
<head>
<script><!-- Loading Scripts -->
function unloadTasks(){
window.alert(":" + playing + ":");
if (playing && !window.confirm("A podcast is playing, and navigating away from this page will stop that. Are you sure you want to go?"))
window.alert("Here is where I will stop the page from unloading... somehow");
}
</script>
<script><!-- Player Scripts -->
var playing = false;
function logPlay(){
playing = isPlaying("e1audPlayer");
}
function isPlaying(player){
return document.getElementById(player).currentTime > 0 && !document.getElementById(player).paused && !document.getElementById(player).ended;
}
</script>
</head>
<body onunload="unloadTasks()">
<audio id="e1audPlayer" style="width:100%;" controls="controls" preload="auto" onplaying="logPlay()" onpause="logPlay()">
<source src="http://s.supuhstar.operaunite.com/s/content/pod/ADHD Episode 001.mp3" type="audio/mpeg"/>
<source src="http://s.supuhstar.operaunite.com/s/content/pod/ADHD Episode 001.ogg" type="audio/ogg"/>
Your browser does not support embedded audio players. Try <a href="http://opera.com/">Opera</a> or <a href="http://chrome.com/">Chrome</a>
</audio>
<a href="http://example.com/">Link away</a>
</body>
</html>