16

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.

P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37
user1990525
  • 3,357
  • 4
  • 16
  • 13
  • What is inside `mymethod();` and how it works in other browsers ? – The Alpha Apr 01 '14 at 04:22
  • I tried simple alert. Even this doesn't work. By the way it does an ajax call. – user1990525 Apr 01 '14 at 04:27
  • using alert in this case might be the worst choice, as browsers try hard to eliminate possibility for the developer to force user to stay at the site, and alert, being a modal function, could be used for that :) – qbolec Oct 21 '14 at 12:01

1 Answers1

41

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.

Update 2021:

Only Internet Explorer supports a custom text message.

Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100