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.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.
Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With