在您重新链接我之前,我已经阅读了诸如如何阻止页面在 JS 中卸载(导航)之类的问题?,但它们处理 HTML4 及以下版本。我想要一个利用 HTML5 事件属性的答案onunload
。我还希望它尽可能纯粹,即没有外部库或插件,如 jQuery 或 Flash,只使用标准化代码(纯HTML、CSS 和 JavaScript,不依赖于平台)。
在你告诉我使用之前onbeforeunload
,请注意它是NON-STANDARD,因此不符合我上面描述的标准。它不适用于所有浏览器,尤其是那些在 IE 实现它之前制作的浏览器。
问题
在我的网站上,我有几个音乐播放器,如果其中任何一个在用户尝试离开页面时正在播放,我想弹出一个对话框,确保他们有意这样做并且他们明白这将停止音频流,如果他们选择“是”或“确定”,则继续导航,但如果他们单击“否”或“取消”,它会停留在同一页面上并不间断地播放音频。如何使用 JavaScript 取消页面卸载而不使用ONBEFOREUNLOAD
?
到目前为止的代码
到目前为止,我有以下代码,但不知道如何停止卸载:
<!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>