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.
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/