为什么jQuery onbeforeunload无法在Chrome和Firefox中使用? [英] Why is jQuery onbeforeunload not working in Chrome and Firefox?

查看:268
本文介绍了为什么jQuery onbeforeunload无法在Chrome和Firefox中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery onbeforeunload在Chrome和Firefox中无法使用.它可以在IE和Safari中正常运行.

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

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

以上代码可在IE和Safari中正常运行,但不能在Firefox和Chrome中运行.

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

推荐答案

根据MDN的 window.onbeforeunload 参考

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

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

观察此jsFiddle

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

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

[...] HTML5规范指出调用window.showModalDialog(), window.alert(),window.confirm()和window.prompt()方法的调用在此事件期间可能会被忽略.

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

关于AJAX的重要说明:

An important note about AJAX:

如果您在用户离开时尝试拨打AJAX呼叫,则请求可能会在完成之前被取消(中断).您可以关闭async选项来解决此问题.例如:

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 async option as a way around this. For example:

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

更新2017年:

Update 2017:

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

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

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

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

Edge和IE仍然支持此功能.

Edge and IE still support this.

这篇关于为什么jQuery onbeforeunload无法在Chrome和Firefox中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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