window.onbeforeunload无法正常工作 [英] window.onbeforeunload not working

查看:456
本文介绍了window.onbeforeunload无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中输入字段保存在更改。在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 occured (ie they've typed something into a textbox, but haven't tabbed out of it).

我已阅读过关于使用window.onbeforeunload的SO文章:
第1条
第2条

I have read the following SO articles on using window.onbeforeunload: article 1 article 2

如果我使用以下内容:

window.onbeforeunload = function() {
    return "onbeforeunload";
}

然后我得到一个带有onbeforeunload的弹出窗口。

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()方法。

还建议通过 addEventListener使用此方法 interface:

It is also suggested to use this through the addEventListener interface:


可以应该处理此事件通过 window.addEventListener() beforeunload 事件。

You can and should handle this event through window.addEventListener() and the beforeunload 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆