Why is jQuery onbeforeunload not working in Chrome and Firefox? [duplicate]

房东的猫 提交于 2019-11-28 12:01:43

According to MDN's window.onbeforeunload reference,

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

Observe this 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 ignored during this event.

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

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

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

Edge and IE still support this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!