对于任何人绊倒这篇文章,这是我用来检测onbeforeunload支持的代码片段,如果浏览器不支持它,我切换到onunload(注意使用jquery,显然不是必需的)。在我的情况下,我使用这个代码(和一些额外的)来检查是否有任何AJAX请求仍然活动,并停止用户导航。请记住,使用onunload并不理想,因为浏览器仍然会离开页面,但至少会让您有机会警告用户数据可能已丢失,并且应该返回并检查。
你会发现我使用可用的isEventSupported()函数在https://github.com/kangax/iseventsupported跨浏览器支持检测可用的事件。
// If the browser supports 'onbeforeunload'
if (isEventSupported('beforeunload', window)) {
$(window).on('beforeunload', function(){
return 'This page is still sending or receiving data from our server, if you recently submitted data on this page please wait a little longer before leaving.';
});
}
// The browser doesn't support 'onbeforeunload' (Such as Opera), do the next best thing 'onunload'.
else {
$(window).on('unload', function(){
alert('This page was still sending or receiving data from our server when you navigated away from it, we would recommend navigating back to the page and ensure your data was submitted.');
});
}
为什么不在歌剧中使用'onuload'? – c69
'在Opera 11.5,body.onunload'工作,除非你调用'window.location.reload()'' – Lyth
<身体onunload的= '警报( “测试”)'>','body.onunload =功能() {警报( “测试”)};'和'body.unload(函数(){警报( “测试”)});'都不要我的机器上工作。歌剧11.51,没有附加组件,Windows 7 64位。 –