83

In my chat application I need to get confirmation from user, when my application closes.

So I used the window.onbeforeunload for confirmation alert and window.onunload for logout().

  1. But both functions are working in IE and Chrome. (Application works fine)

  2. window.onbeforeunload not working in Opera and my message will not get displayed in Firefox.

  3. window.onunload not working in Safari, Opera and Firefox.

My JavaScript code will be:

// Used for confirmation, to closing the window 
window.onbeforeunload = function () {

    return  "Are you sure want to LOGOUT the session ?";
}; 

// Used to logout the session, when browser window was closed 
window.onunload = function () {

    if((sessionId != null)&&(sessionId!="null")&& (sessionId != ""))
        logout();
};

I also tried the same function with JQuery,

<script type="text/javascript">

    $(window).on('beforeunload', function() {
        return 'Are you sure want to LOGOUT the session ?';
    });

    $(window).unload(function() {
        if ((sessionId != null) && (sessionId != "null") && (sessionId != "")) {
            logout();
        }
    });
    
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Human Being
  • 8,269
  • 28
  • 93
  • 136
  • Works on my Firefox, except that the message isn't the one you sent. http://jsfiddle.net/yhx6d/ – Fabrício Matté Feb 01 '13 at 11:12
  • Thanks for your reply ... Yes message will not displayed.Also **logout()** is not working.It means **window.onunload()** is not working ? – Human Being Feb 01 '13 at 11:17
  • **window.onbeforeunload** and **window.onunload** not working in opera ? – Human Being Feb 01 '13 at 11:21
  • 1
    Opera [doesn't support](http://stackoverflow.com/questions/4683221/cross-browser-onunload-and-onbeforeunload-particularly-opera-11) `onbeforeunload` and its support of `onunload` in incomplete. – Marcel Korpel Feb 01 '13 at 12:03
  • @ Marcel Korpel Thanks for your reply ... **onunload** in incomplete means . what you are saying ? Cant understand. – Human Being Feb 01 '13 at 12:05
  • `onunload` doesn't fire on all occasions, AFAIK not when using the back button and other similar events (just follow the link I supplied). BTW, you should call me without a space between the at-sign and my name. – Marcel Korpel Feb 01 '13 at 12:41
  • @RobW: Did you actually test that? Opera 12.12 on Linux says `false` to `'onbeforeunload' in window`. – Marcel Korpel Feb 01 '13 at 14:05
  • @MarcelKorpel Tested in 12.50, and it does not exists (even though an Opera representative [announced support in this comment](http://stackoverflow.com/questions/9727344/javascript-how-can-i-tell-browser-chrome-firefox-safari-to-allow-me-to-have#comment12378356_9727366)). (note: To test whether the event is supported, just check if `window.onbeforeunload === null`). – Rob W Feb 01 '13 at 14:54
  • 1
    kindly check http://stackoverflow.com/questions/5548505/post-call-is-not-happening-in-safari for firefox issue – mymotherland Feb 07 '13 at 08:15
  • @Dinesh Thanks for your reply.It worked in all browsers except **opera**. – Human Being Feb 07 '13 at 08:28

6 Answers6

104

Unfortunately, the methods you are using are unsupported in those browsers. To support my answer (this unsupportive behaviour) I have given links below.

onbeforeunload and onunload not working in opera... to support this

onbeforeunload in Opera
http://www.zachleat.com/web/dont-let-the-door-hit-you-onunload-and-onbeforeunload/

Though the onunload event doesn't work completely, you can use onunload to show a warning if a user clicks a link to navigate away from a page with an unsaved form.

onunload not working in safari... to support this

https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/

You could rather try using the pagehide event in the safari browser in lieu of onunload.

onunload not working in firefox... to support this

https://bugzilla.mozilla.org/show_bug.cgi?id=681636

They are yet to come up with a solution in FF too.

starball
  • 20,030
  • 7
  • 43
  • 238
Freakyuser
  • 2,774
  • 17
  • 45
  • 72
  • 44
    I gave **+50** bounty to you.Because you worked a lot to get this suggested answer.And it is helped for other questions. – Human Being Feb 07 '13 at 08:47
  • 3
    any updates ? still not supported ?, any workarounds ? – Francisco Corrales Morales Jun 25 '14 at 04:02
  • The link you shared to support the statement that `onunload` doesn't work in firefox, is meant when the page is in a popup situation only. "window.onUnload don't work when the page is in a popup" – Nick Rolando Apr 19 '18 at 20:54
  • This reliably works for me provided that I interact with the page first (eg. click on the page). If I simply hit command-r before an interaction, the dialog does not reliably appear across the browsers I tested (FF, Safari, Chrome, and Opera) on OSX. – Paul Jan 14 '21 at 02:58
45

Here is the working solution for ie, firefox and chrome:

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable

            myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                var confirmationMessage = 'Are you sure to leave the page?';  // a space
                (e || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            });
faisale
  • 1,435
  • 14
  • 14
  • @user3253009.how do you find the response here ? – KumarHarsh Jul 30 '14 at 07:44
  • Which response @KumarHarsh? – faisale Aug 18 '14 at 22:24
  • @user3253009,when pop up appear with "Stay on Page" or "Leave the page" then can we catch the response whether user has click which button . – KumarHarsh Aug 20 '14 at 07:27
  • no @KumarHarsh you can't catch the response, it is browser behavior, either you can stay or leave the page. – faisale Aug 24 '14 at 10:33
  • This does not work on all browsers(Firefox 36.0.4). I found out the answer given [here](http://stackoverflow.com/questions/22776544/why-is-jquery-onbeforeunload-not-working-in-chrome-and-firefox?lq=1) that is tested and works on ie,firefox,safari and chrome. – Sumedha Vangury Apr 06 '15 at 11:48
  • 2
    @user3253009, great! But seems it doesn't work on safari on iPhone. Any possibnle workaround for this? – user2335065 Jul 05 '15 at 16:08
  • It works for me. Can you explain how can i detach this event? Аfter your code. – jekaby Apr 15 '16 at 11:43
  • Thank you, works for me! I tested in Chrome 50, Firefox 46, and IE11. It shows the prompt on page reload, back button, links, and closing browser window/tab. I am surprised that jQuery unload method doesn't work this well. – Gerry May 23 '16 at 15:03
  • @faisale how can I leave the page without prompting user? – sadia Nov 17 '16 at 12:45
  • @diyasher which prompt you are talking about? Like firefox prompt before leaving browser if more than one tab is opened? – faisale Dec 12 '16 at 11:37
17

I was able to get it to work in IE and FF with jQuery's:

$(window).bind('beforeunload', function(){

});

instead of: unload, onunload, or onbeforeunload

nathan hayfield
  • 2,627
  • 1
  • 17
  • 28
14

I got the solution for onunload in all browsers except Opera by changing the Ajax asynchronous request into synchronous request.

xmlhttp.open("POST","LogoutAction",false);

It works well for all browsers except Opera.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Human Being
  • 8,269
  • 28
  • 93
  • 136
  • it works in firefox, but unfortunately [mdn says](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Types_of_requests) its supposedly deprecated – oldboy Jul 28 '19 at 20:40
7

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};
leeway
  • 485
  • 1
  • 3
  • 9
  • 3
    Seems like a very unsafe thing to do. To be able to automatically log the user back in credentials must be stored in the browser which basically allows a logged out user to be logged in by anyone. – Niclas Aug 20 '15 at 13:23
2

Firefox simply does not show custom onbeforeunload messages. Mozilla say they are protecing end users from malicious sites that might show misleading text.

anoldermark
  • 366
  • 3
  • 8