Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 523
user1990525 Avatar asked Apr 01 '14 03:04

user1990525


People also ask

What triggers Onbeforeunload?

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.

What is Onbeforeunload?

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.

How do you cancel Windows Onbeforeunload?

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.


1 Answers

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.

like image 181
Rowan Freeman Avatar answered Sep 19 '22 14:09

Rowan Freeman