对于任何偶然发现这篇文章的人,这是我用来检测 onbeforeunload 支持的代码片段,如果浏览器不支持它,我会切换到 onunload(注意使用 jquery,显然不是必需的)。在我的例子中,我使用这段代码(以及一些额外的代码)来检查是否有任何 AJAX 请求仍然处于活动状态并阻止用户导航。请记住,使用 onunload 并不理想,因为浏览器仍会离开页面,但至少它让您有机会警告用户数据可能已丢失,他们应该返回并检查。
您会注意到我正在使用https://github.com/kangax/iseventsupported提供的 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.');
});
}