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 applicati
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?
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.
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.