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

标签 jquery onbeforeunload

jQuery onbeforeunload在 Chrome 和 Firefox 中不起作用。它在 IE 和 Safari 中工作正常。

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

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

最佳答案

根据 MDN 的 window.onbeforeunload引用,

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

观察this jsFiddle

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

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

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

关于 AJAX 的重要说明:

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

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

2017 年更新:

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

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

Edge 和 IE 仍然支持此功能。

2021 年更新:

只有 Internet Explorer 支持自定义文本消息。

关于jquery - 为什么 jQuery onbeforeunload 在 Chrome 和 Firefox 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22776544/

相关文章:

javascript - 将单选按钮更改为图像会导致 jquery 验证丢失

jquery - 居中较小的 Jquery Mobile HTML 自定义加载微调器

javascript - 从二维 Javascript 数组中删除一个项目

javascript - 不要从表 td 第一个子元素中删除内容

javascript - 如何通过 Selenium 处理下面的 Internet Explorer 弹出窗口 "Are you sure you want to leave this page?"

javascript - 使用 JavaScript 防止网页导航离开

javascript - 如何防止在 chrome 中使用 'onbeforeunload' 事件进行双重确认

javascript - onbeforeunload 在 chrome 上不起作用

javascript - 刷新页面后图片位置不正确

window.onbeforeunload 中的 Javascript 返回在 chrome 中不起作用