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

Pointy
  • 405,095
  • 59
  • 585
  • 614
Ansh Jain
  • 73
  • 1
  • 4

3 Answers3

4

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
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 3
    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). – jimbo May 26 '10 at 15:06
  • 1
    Call `setTimeout` to make an AJAX request every minute. – SLaks May 26 '10 at 15:09
  • If I have thousand of user online at a time then every interval it will send 1000 of request to my web server without any reason. I this case I would suggest keep a record of user last activity time in a activity table. Run a cornjob in a background which will make users logout and clear there session those who are more than 30 mins inactive. – Amar Banerjee Jun 12 '13 at 14:43
2

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
  • 8,226
  • 7
  • 45
  • 90
  • 1
    unload is not useful at all the times, lets say when you close the browser, you are asking to execute something after page unload, but now the browser process itself is not live so it wont execute the unload function. So onbeforeunload is the best option.. – Seeker Aug 06 '12 at 13:13
1

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
  • 16,230
  • 17
  • 74
  • 137