如果用户在不保存表单的情况下尝试关闭窗口,我将显示警告消息。
window.onbeforeunload = askConfirm;
function askConfirm()
{
// needToConfirm is set to true if any changes are there in the form
if (needToConfirm)
{
return "Your unsaved data will be lost.";
}
}
function call_this_if_user_clicks_on_cancel()
{
// Bla bla bla
// After this user should remain on the same page.
}
现在,我想在用户单击Okay
时调用另一个函数。其余功能应保持不变。那么,如何收集onbeforeunload
返回值并调用另一个函数呢?
SOLUTION:
needToConfirm = false;
window.onbeforeunload = askConfirm;
window.onunload = unloadPage;
isDelete = true;
function unloadPage()
{
if(isDelete)
{
call_this_if_user_clicks_on_cancel()
}
}
function askConfirm()
{
alert("onbeforeunload");
if (needToConfirm)
{
// Message to be displayed in Warning.
return "Your data will be lost.";
}
else
{
isDelete = false;
}
}
我不确定;但是我认为您不能调用另一个函数,这是浏览器的一种预防措施,因此它不会因离开页面而陷入困境。
我认为只有浏览器才能知道它是否返回true / false,以确定页面是否已卸载。
以前unbeforeunload是非标准的(从IE4开始,但受其他浏览器支持)这是Mozilla文档https://developer.mozilla.org/en/DOM/window.onbeforeunload和Microsoft文档:http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
但是看起来HTML5提案中的BeforeUnloadEvent看起来像。本文档详细介绍了卸载文档时所发生的步骤(有趣的阅读内容):
http://www.w3.org/TR/html5/history.html#beforeunloadevent
作为解决方法:您可能能够从“卸载事件”中收集所需的信息,如果在onbeforeunload之后未调用卸载事件,则可以假定用户选择停留在您的页面上。