Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure code is always called before page unload

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?

like image 796
Steven Lu Avatar asked Nov 03 '22 18:11

Steven Lu


2 Answers

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.

like image 59
epascarello Avatar answered Nov 12 '22 14:11

epascarello


window.onunload=function(){
//your code here
}

i guess we do have this.

like image 22
Apurv Avatar answered Nov 12 '22 15:11

Apurv