为什么 jQuery onbeforeunload 在 Chrome 和 Firefox 中不起作用?

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

Why is jQuery onbeforeunload not working in Chrome and Firefox?

jqueryonbeforeunload

提问by user1990525

jQuery onbeforeunloadis not working in Chrome and Firefox. It works properly in IE and Safari.

jQueryonbeforeunload不适用于 Chrome 和 Firefox。它在 IE 和 Safari 中正常工作。

jQuery(window).bind('onbeforeunload' ,function () {
    mymethod();
});

Above code works properly in IE and in Safari but not in Firefox and Chrome.

以上代码在 IE 和 Safari 中正常工作,但在 Firefox 和 Chrome 中不能正常工作。

回答by Rowan Freeman

According to MDN's window.onbeforeunloadreference,

根据 MDN 的window.onbeforeunload参考,

The function should assign a string value to the returnValue property of the Event object and return the same string.

该函数应为 Event 对象的 returnValue 属性分配一个字符串值并返回相同的字符串。

Observe this jsFiddle

观察这个jsFiddle

jQuery(window).bind('beforeunload', function(e) {
    var message = "Why are you leaving?";
    e.returnValue = message;
    return message;
});

Note that certain events may be ignored:

请注意,某些事件可能会被忽略

[...] the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignoredduring this event.

[...] HTML5 规范声明在此事件期间可以忽略对 window.showModalDialog()、window.alert()、window.confirm() 和 window.prompt() 方法的调用。

An important note about AJAX:

关于 AJAX 的一个重要说明:

If you're trying to make an AJAX call when the user is leaving the request may be cancelled (interrupted) before it finishes. You can turn off the asyncoption as a way around this. For example:

如果您在用户离开时尝试进行 AJAX 调用,则请求可能会在完成之前被取消(中断)。您可以关闭该async选项作为解决此问题的方法。例如:

$.ajax({
    url: "/",
    type: "GET",
    async: false
});

Update 2017:

2017 年更新:

Many browsers no longer support custom text in the alert dialog when the user is leaving.

当用户离开时,许多浏览器不再支持警报对话框中的自定义文本。

The latest versions of Chrome, Firefox, Opera and Safari do not display any custom text.

最新版本的 Chrome、Firefox、Opera 和 Safari 不显示任何自定义文本。

Edge and IE still support this.

Edge 和 IE 仍然支持这一点。