Ansh Jain
Ansh Jain

Reputation: 73

want to detect browser close event?

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

Upvotes: 3

Views: 4629

Answers (3)

Bruno Brant
Bruno Brant

Reputation: 8564

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.

Upvotes: 2

graham.reeds
graham.reeds

Reputation: 16486

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?

Upvotes: 1

SLaks
SLaks

Reputation: 888203

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.

Upvotes: 4

Related Questions