I have an asynchronous funcion (closing a socket) that I have to execute when the user leaves the page. I’ve tried to do it through jQuery :
$(window).unload(function() {
socket.disconnect();
});
However, this doesn’t work because the function is asynchronous and the client leaves the page as soon as it reach the end of the method, that’s to say instantly and the request to disconnect the socket is not performed.
We can provide a callback executed at the end of the socket.disconnect() function execution. Maybe this could help…
Is there a way in javascript to solve this ?
I’m going to stick my neck out and say that I don’t believe this is viable – at least not cross-browser.
As one suggested, you can interrupt navigation via
onbeforeunloadbut this is not implemented the same cross-browser, and even if you can interrupt it, you can’t (I believe) capture where the user was going, such that, in your socket closure callback, you could then forward them on.An unideal compromise might be to use
onbeforeunloadto at least prompt them to manually disconnect from the server. Many will; those that don’t you can pick up with server-side detection.