Human Being Human Being - 2 months ago 80
Javascript Question

window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?

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>

Answer

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.