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 开发者_StackOverflowthe 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
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.
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?
精彩评论