Answers:
与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;
};
var foo, bar;
与var foo;
var bar;
请参阅本文。您正在寻找的功能是onbeforeunload
样例代码:
<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>
与其烦人的确认弹出窗口,不如延迟一小段时间(毫秒)来成功地将未保存的数据成功发布到服务器,这是我很好的做法,我使用这样的虚拟文本向控制台进行管理:
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
编辑: 另请参见Synchronous_AJAX以及如何使用jquery
SCHEDULED_REQUEST
的对象累积了应该发送到服务器的任何非紧急信息(例如数据缓冲区),从而有效地将多个请求连接到一个请求(当然,这些请求的url是相同的)。如前所述,在卸载之前使用Synchronous Ajax请求可以解决跨浏览器的问题。感谢您的宝贵意见!
我的用户尚未完成所有必需的数据。
<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>