See the answer here: Javascript register window/tab closing event before window/tab close.
Using the window.onbeforeunload
(MDN article) event, you can assign an event listener to fire off an AJAX call that can finalize your XmppClient
:
window.onbeforeunload = function (event) {
$.ajax('/api/route/specifically/to/finalize/xmpp')
};
Of course, be sure to check that the browser compatibility (MDN) is what you require. Edge, for example, does not support this event. IE is apparently iffy when it comes to that specific event handler. You can also refer to an alternative "beforeunload" event that is apparently more widely supported. It would look like this:
window.addEventListener("beforeunload", function (event) {
$.ajax('/api/route/specifically/to/finalize/xmpp')
});
Also be aware that this won't work if the browser crashed, for example, or some other unexpected event causes the window to close where the browser may not be able to fire that event before the window closes.
You might also consider the Session_End
event in Global.aspx
: On-Session-expire-event? and MSDN article:
public void Session_OnEnd()
{
Application.Lock();
Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;
Application.UnLock();
}
That will run (according to MSDN) "when the Abandon method has been called or when the session has expired."