Intercept page exit event

在我的系统中编辑页面时,用户可能决定导航到另一个网站,这样做可能会丢失所有未保存的编辑内容。

我希望拦截任何转到另一个页面的尝试,并提示用户确保他们希望发生这种情况,因为他们可能会失去当前的工作。

Gmail 也是这样做的。例如,撰写一封新的电子邮件,开始在邮件正文中键入内容,然后在地址栏中输入一个新的位置(比如 twitter.com 或者其他)。它会提示你问“你确定吗?”

我的目标是 IE8,但是也想兼容 Firefox 和 Chrome。

160677 次浏览

看看这篇文章。 您正在寻找的特性是在卸载之前的“ norefrer”

示例代码:

  <script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}
</script>

与 Ghommey 的回答相似,但是它也支持旧版本的 IE 和 Firefox。

window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}


// For Safari
return message;
};

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
// only take action (iterate) if my SCHEDULED_REQUEST object contains data
for (var key in SCHEDULED_REQUEST){
postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
for (var i=0;i<1000;i++){
// do something unnoticable but time consuming like writing a lot to console
console.log('buying some time to finish saving data');
};
break;
};
}; // no return string --> user will leave as normal but data is send to server

编辑: 另请参阅 同步 _ AJAX以及如何使用 < a href = “ https://stackoverflow. com/a/1572646/847331”> jquery 完成此操作

我有没有完成所有必需数据的用户。

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
<cfset unloadCheck=1>
$("#myInput").change(function(){
verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
});
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
verify();
window.onbeforeunload = confirmExit;
function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>