There are many discussions of the Window: beforeunload event on Stack Overflow.
My specific problem is that my beforeunload event is not being called when a user closes a tab in Chrome (v91.0.) if the page is processing other JavaScript.
Is there anyway to guarantee the firing of the beforeunload event?
Specifically what I am trying to do is when a user closes a tab or the browser the beforeunload event is called and that listener function makes a call to another function that makes an Ajax call to an action class that signals the server that the user is no longer active (and resources can be released); maybe there is a better way to do this.
Here is the code for the listener:
window.addEventListener('beforeunload', function (e) {
setExternalUserStatus(false);
});
Here is the code for the AJAX call :
function setExternalUserStatus(externalUserStatus) {
if (!xmlhttpLogger) {
createXMLHttpRequestLogger();
}
xmlhttpLogger.open("POST", "../../geospatial/setExternalUserStatus.action?externalUserStatus=" + externalUserStatus);
xmlhttpLogger.setRequestHeader("pragma", "no-cache");
xmlhttpLogger.setRequestHeader("Cache-Control", "no-cache,max-age=0");
xmlhttpLogger.send(null);
xmlhttpLogger.onreadystatechange = function () {
if (xmlhttpLogger.readyState === 4) {
if (xmlhttpLogger.status === 200) {
if (xmlhttpLogger.responseText.includes("updated")) {
console.debug("ExternalUserStatus updated.")
} else {
console.debug("ExternalUserStatus NOT updated.")
}
} else {
console.log("Server status: " + xmlhttpLogger.status)
}
}
}
}
Thx in advance.