Javascript 捕获 window.onbeforeunload

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7255649/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:30:22  来源:igfitidea点击:

Capturing window.onbeforeunload

javascriptdom-events

提问by Joe

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 onBlurevent hasn't occurred (i.e. they've typed something into a textbox, but haven't tabbed out of it).

我有一个表单,其中保存了输入字段onChange。在 Firefox (5) 中,即使窗口关闭也能正常工作,但对于 Chrome 和 IE 则不行,我需要确保我正在保存这些数据,即使他们在输入后尝试关闭窗口一个字段但onBlur尚未发生事件(即他们已在文本框中键入了一些内容,但尚未将其移出)。

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

我已阅读以下有关使用的 SO 文章window.onbeforeunload文章 1文章 2

if I use the following:

如果我使用以下内容:

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

then I get a popup with onbeforeunloadin.

然后我得到一个弹出窗口onbeforeunload

but if I try:

但如果我尝试:

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

then nothing happens in any browser, even Firefox.

然后在任何浏览器中都不会发生任何事情,即使是 Firefox。

what I want to achieve is:

我想要实现的是:

window.onbeforeunload = function() {
    saveFormData();
}

I'd be grateful if someone could point out where I might be going wrong.

如果有人能指出我可能出错的地方,我将不胜感激。

回答by epoch

You have to returnfrom the onbeforeunload:

你必须returnonbeforeunload

window.onbeforeunload = function() {
    saveFormData();
    return null;
}

function saveFormData() {
    console.log('saved');
}

UPDATE

更新

as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)

根据评论,警报似乎不再适用于较新版本,其他任何事情都可以:)

FROM MDN

来自MDN

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt()methods may be ignored during this event.

自2011年5月25日,在HTML5规范规定调用window.showModalDialog()window.alert()window.confirm(),和window.prompt()方法可以此事件中被忽略。

It is also suggested to use this through the addEventListenerinterface:

也建议通过addEventListener接口使用这个:

You canand shouldhandle this event through window.addEventListener()and the beforeunloadevent.

可以应该处理通过这次活动window.addEventListener()beforeunload事件。

The updated code will now look like this:

更新后的代码现在看起来像这样:

window.addEventListener("beforeunload", function (e) {
  saveFormData();

  (e || window.event).returnValue = null;
  return null;
});

回答by Adam

There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).

似乎有很多关于如何使用此事件的错误信息(即使在此页面上的赞成答案中)。

The onbeforeunloadevent API is supplied by the browser for a specific purpose: The only thing you can dothat's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page(imagine what a nightmare that would be for the end user).

onbeforeunload事件API是由浏览器为特定目的而提供的:唯一你可以做在这个方法中值得做的是返回一个字符串,然后浏览器将提示用户向他们指示应该在他们离开页面之前采取行动。你不能阻止他们离开页面(想象一下这对最终用户来说是一场噩梦)。

Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).

因为浏览器使用确认提示向用户显示您从事件侦听器返回的字符串,所以您也不能在该方法中执行任何其他操作(例如执行 ajax 请求)

In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.

在我编写的应用程序中,我想提示用户在离开页面之前让他们知道他们有未保存的更改。浏览器会用消息提示他们,之后,我就无法控制了,用户可以选择留下或离开,但此时您不再拥有对应用程序的控制权。

An example of how I use it (pseudo code):

我如何使用它的示例(伪代码):

onbeforeunload = function() {

  if(Application.hasUnsavedChanges()) {
    return 'You have unsaved changes. Please save them before leaving this page';
  }


};

If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.

如果(且仅当)应用程序有未保存的更改,则浏览器会提示用户忽略我的消息(无论如何都离开该页面)或不离开该页面。如果他们无论如何都选择离开页面,那太糟糕了,您对此无能为力(也不应该做)。

回答by Alireza Rinan

you just cant do alert() in onbeforeunload, anything else works

您不能在 onbeforeunload 中执行 alert(),其他任何操作都可以

回答by OG Sean

To pop a message when the user is leaving the page to confirm leaving, you just do:

要在用户离开页面时弹出消息以确认离开,您只需执行以下操作:

<script>
    window.onbeforeunload = function(e) {
      return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    };
</script>

To call a function:

调用函数:

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>

回答by Panu Logic

The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."

使用 'alert()' 时什么都没有发生的原因可能正如 MDN 所解释的:“HTML 规范指出,对 window.alert()、window.confirm() 和 window.prompt() 方法的调用可能会被忽略在这次活动中。”

But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:

但是,您可能根本看不到警告还有另一个原因,无论它是否调用 alert(),也在同一站点上进行了解释:

"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"

“...浏览器可能不会显示在 beforeunload 事件处理程序中创建的提示,除非页面已与之交互”

That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:

这就是我在当前版本的 Chrome 和 FireFox 中看到的。我打开我的页面,其中使用以下代码设置了 beforeunload 处理程序:

window.addEventListener
('beforeunload'
, function (evt)
  { evt.preventDefault();
    evt.returnValue = 'Hello';
    return "hello 2222"
  }
 );

If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.

如果我没有点击我的页面,换句话说,“不要与之交互”,然后点击关闭按钮,窗口会在没有警告的情况下关闭。

But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.

但是如果我在尝试关闭窗口或选项卡之前点击页面,我会收到警告,并且可以取消关闭窗口。

So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.

因此,这些浏览器是“智能的”(并且用户友好),因为如果您尚未对页面进行任何操作,则它不会有任何需要保存的用户输入,因此它们将关闭窗口而不会发出任何警告。

Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.

考虑到如果没有此功能,任何网站可能会自私地问您:“您真的要离开我们的网站吗?”,当您已经明确表示您打算离开他们的网站时。

SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

参见:https: //developer.mozilla.org/en-US/docs/Web/Events/beforeunload

回答by ThePennyDrops

I seem to be a bit late to the party and much more of a beginner than any expertise; BUT this worked for me:

我参加聚会似乎有点晚了,而且比任何专业知识都更像是初学者;但这对我有用:

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


I placed this as an inline script immediately after my Head and Meta elements, like this:


我将它作为内联脚本放在 Head 和 Meta 元素之后,如下所示:

<script>
  window.onbeforeunload = function() {
     return false;
  }
</script>

This page seems to me to be highly relevant to the originator's requirement (especially the sections headed window.onunloadand window.onbeforeunload): https://javascript.info/onload-ondomcontentloaded

在我看来,此页面与发起者的要求高度相关(尤其是标题为window.onunload和的部分window.onbeforeunload):https: //javascript.info/onload-ondomcontentloaded

Hoping this helps.

希望这会有所帮助。

回答by OsamaBinLogin

Yes what everybody says above.

是的,上面每个人都说。

For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.

对于您的当前情况,您可以使用 html5 中的 onInput,而不是 onChange。input 事件是相同的,但它会在每次击键时触发,无论焦点如何。也适用于选择和所有其他的,就像 onChange 一样。