捕获window.onbeforeunload [英] Capturing window.onbeforeunload
问题描述
我有一个表单,其中输入字段保存在 onChange
中。在Firefox(5)中,即使关闭了窗口,此方法仍然有效,但对于Chrome和IE则不起作用,即使他们输入后试图关闭窗口,我也需要确保我保存了这些数据一个字段,但是没有发生 onBlur
事件(即,他们已经在文本框中键入了一些内容,但没有在其中跳出标签)。
I have a form where the input fields are saved onChange
. In Firefox (5) this works even when the window is closed, but for Chrome and IE it doesn't and I need to be sure that I'm saving this data even if they try to close the window after they've typed in a field but an onBlur
event hasn't occurred (i.e. they've typed something into a textbox, but haven't tabbed out of it).
我已阅读以下有关使用 window.onbeforeunload
的文章:
< a href = https://stackoverflow.com/questions/1244535/alert-when-browser-window-closed-accidentally>第2条
I have read the following SO articles on using window.onbeforeunload
:
article 1
article 2
如果我使用以下命令:
window.onbeforeunload = function() {
return "onbeforeunload";
}
然后我在弹出窗口中弹出
in。
then I get a popup with onbeforeunload
in.
但是如果我尝试:
window.onbeforeunload = function() {
alert("onbeforeunload");
}
然后在任何浏览器(甚至是Firefox)中都不会发生任何事情。
then nothing happens in any browser, even Firefox.
我要实现的是:
window.onbeforeunload = function() {
saveFormData();
}
如果有人可以指出我可能会出问题的地方,我将不胜感激。
I'd be grateful if someone could point out where I might be going wrong.
推荐答案
您必须从返回
> onbeforeunload :
You have to return
from the onbeforeunload
:
window.onbeforeunload = function() {
saveFormData();
return null;
}
function saveFormData() {
console.log('saved');
}
更新
根据评论,警报似乎不再适用于较新的版本,其他任何事情都会发生:)
as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)
FROM MDN
自2011年5月25日起,HTML5规范规定调用
window.showModalDialog()
,window.alert()
,window.confirm()
和window.prompt()
方法在此事件期间可能会被忽略。
Since 25 May 2011, the HTML5 specification states that calls to
window.showModalDialog()
,window.alert()
,window.confirm()
, andwindow.prompt()
methods may be ignored during this event.
还建议通过 addEventListener使用此方法
界面:
您可以并且应该处理该事件通过
window.addEventListener()
和beforeunload
事件进行。
You can and should handle this event through
window.addEventListener()
and thebeforeunload
event.
更新后的代码如下所示:
The updated code will now look like this:
window.addEventListener("beforeunload", function (e) {
saveFormData();
(e || window.event).returnValue = null;
return null;
});
这篇关于捕获window.onbeforeunload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!