Usually this isn't important, and it may not even be too important for my situation, but I'd like to know if there is a reasonable way to implement this.
My page automatically opens a web socket connection. In order to be a better client I want the client to clean up after itself and close the websocket before the page gets unloaded.
My hope is that the browser would have the foresight to call close()
for me when the page is unloaded, but in case it doesn't, how can I leverage the onbeforeunload
message (or some such) to do some "final cleanup" (not unlike atexit()
in C)?
Suppose I have some system where I want my clients to send an "exiting" message to my websocket server for some reason.
I can do this now:
$(window).on('beforeunload', function () {
websocket.close(); // websocket is a WebSocket
});
But suppose close()
is actually an asynchronous call (is it?) and I want to make sure the socket.onclose callback fires prior to actually unloading the page! Can this be done?
There is no sure fire way of making sure an asynchronous call is fully executed in modern browsers. Older versions could be held up with a while loop, but current browsers will kill any process and continue. Reason is they want the user experience to be fast, you holding them up does them harm.
window.onunload=function(){
//your code here
}
i guess we do have this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With