tags:

views:

96

answers:

3

I am working on any application in which i need to detect that whether user close the tab or browser so I can disconnect the user from other user basically its an chat application.

I have used :-

window.onbeforeunload = confirmExit;

function confirmExit() { 
    if(needToConfirm) {
        return "Leaving this page will end your conversation.";
    }

Its work fine, when I try to close the browser or tab it shows an popup with message "Press OK to continue, or Cancel to stay on the current page." I want to perform task when user click on Ok button and if he press cancel then will stay on current page.

Please Help me :(

Thanks in advance

Ansh J

+4  A: 

This is not possible.

You could handle the unload event and send an AJAX request there, but that might not be completely reliable.

The best solution is to send an AJAX hearbeat every x minutes, and consider the user disconnected if you stop receiving the heartbeat.

SLaks
Could you please give me a sample code which will help me
Ansh Jain
This would also handle the case where the user's browser crashes, or they lose connectivity for some reason (network goes down, poor coverage, etc).
jimbojw
Call `setTimeout` to make an AJAX request every minute.
SLaks
+1  A: 

Why not have the client's periodically 'ping' the server to let it know that they are still there, and if a user misses say 3 pings then it will be marked as logged off?

graham.reeds
+1  A: 

Go the other way around: when you receive the Unload event, send the server a message that informs the user is about to disconnect. The server waits for some time and then automatically disconnects.

Then, if the user click cancel and stays on the page, you send a message to the server to inform that the client is still alive.

The downside is that, if the user waits too long to click cancel, he might be disconnected.

Bruno Brant