0

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.

user2782
  • 358
  • 2
  • 18
  • related to this? https://stackoverflow.com/questions/60217338/event-onbeforeunload-isnt-fired-in-chrome-incognito or this? https://stackoverflow.com/questions/9626059/window-onbeforeunload-in-chrome-what-is-the-most-recent-fix – Kinglish Jul 12 '21 at 23:32
  • Not incognito and I am not trying to display a popup. I just want the event to fire. We have an application with some really intense JavaScript. When that JavaScript is firing, the beforeunload event does not fire, the page just closes. I think this is a bug in Chrome. Unfortunately, we are in a very restricted environment that only allows Chrome. – user2782 Jul 12 '21 at 23:46
  • The exact same behavior is confirmed in the new Microsoft Edge browser, so this is most likely a bug in Chromium. – user2782 Jul 13 '21 at 12:25

0 Answers0