javascript 如何收集onbeforeunload的返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6579509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to collect return value of onbeforeunload
提问by xyz
I am displaying a warning message if user try to close window without saving the form.
如果用户尝试关闭窗口而不保存表单,我将显示一条警告消息。
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.
}
Now I want to call another function when user clicks on Okay
. And rest of the functionality should remain same.
So how can I collect onbeforeunload
return value and call another function ?
现在我想在用户点击时调用另一个函数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;
}
}
采纳答案by Alex KeySmith
I'm not certain; But I would of thought you cannot call another function, as a preventative measure by the browser so it doesn't get trapped from leaving the page.
我不确定;但我认为你不能调用另一个函数,作为浏览器的一种预防措施,这样它就不会因为离开页面而被困住。
I think only the browser knows if it's returns true / false to determine if the page is unloaded (or not).
我认为只有浏览器知道它是否返回 true / false 以确定页面是否已卸载(或未卸载)。
Previously unbeforeunload was non-standard (from IE4, but supported by other browsers) Here are the Mozilla docs https://developer.mozilla.org/en/DOM/window.onbeforeunloadAnd Microsoft docs: http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
以前 unbeforeunload 是非标准的(来自 IE4,但其他浏览器支持)这里是 Mozilla 文档https://developer.mozilla.org/en/DOM/window.onbeforeunload和 Microsoft 文档:http: //msdn.microsoft。 com/en-us/library/ms536907(VS.85).aspx
However it looks as thought BeforeUnloadEvent is in the HTML5 proposal. This document gives in detail the steps that happen when a document is unloaded (interesting read):
然而,看起来 BeforeUnloadEvent 是在 HTML5 提案中。本文档详细介绍了卸载文档时发生的步骤(有趣的阅读):
http://www.w3.org/TR/html5/history.html#beforeunloadevent
http://www.w3.org/TR/html5/history.html#beforeunloadevent
As a workaround: You may be able to gather the information you need from the "unload event", if the unload event is NOT called after the onbeforeunload, you could assume that the user chose to stay on your page.
解决方法:您可以从“卸载事件”中收集所需的信息,如果在 onbeforeunload 之后未调用卸载事件,您可以假设用户选择留在您的页面上。