$(window).unload not working as expected

I’m making a small chat application with PHP + MySQL + JavaScript, I’ve written a function disonnectUser(), which is called when the user press the disconnect button. Here it is:

function disconnectUser(){
            $.post('web/WEB-INF/classes/handleChatUser.php',{ action: 'disconnect',nick: localNickname});           
            $('#chat').stop(true,true).fadeOut(2000,function(){
                nicknameDialog();
            });

            $('#messageInput').val(null);
            $('#clientList').html(null);
            $('#chatScreen').html(null);
            clearInterval(refreshIntervalId);
            clearInterval(refreshIntervalId2);
            connected = false;
        }

And it works like a charm, but when I call this very function in another context, when the user instead of pressing disconnect just exit the page, in this function

$(window).unload(function() {
                if(connected){
                disconnectUser();
                connected = false;
                }
            });

it doesn’t work. And I’m sure it’s being called, because if I put an alert it’s called normally before closing the page. I think the page is closing before the code runs completely, so I think if I put some block there until the code finish running it would work?

Answer

Instead of unload, how about beforeunload?

window.onbeforeunload = function() {
    if(connected){
        disconnectUser();
        connected = false;
    }
};

Also, your disconnectUser method already sets connected to false, no need to do it here also.

It also seems that jQuery doesn’t really handle the beforeunload event, which is why you’ll need to revert to native JS to handle this:

http://groups.google.com/group/jquery-en/browse_thread/thread/4e5b25fa1ff5e5ee?pli=1

Leave a Reply

Your email address will not be published. Required fields are marked *