Why is jQuery onbeforeunload not working in Chrome and Firefox?

user1990525 picture user1990525 · Apr 1, 2014 · Viewed 36.7k times · Source

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

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

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

Answer

Rowan Freeman picture Rowan Freeman · Apr 1, 2014

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.