Auto Log Out on browser or browser tab close?

Simple request … is it possible to auto logout of a web app if the browser or browser tab is closed?

1 Like

In Security Login step you have a field “Remember” that accepts a boolean (true/false) to indicate if the session should persist or not (on browser close).

“Auto logout” itself is not a feature that exists. One could make some shenanigan with WebSockets to detect when a browser tab is closed, but that’s not a standard practice.

I should add that I am using PHP. I don’t have access to Node.js hosting.

1 Like

Hi Brad, u can do that using the JS event beforeunload. Here u have how to do it.

2 Likes

thanks Max, I did try …

  <script>
    window.addEventListener('beforeunload', function (e) {
      // Cancel the event
      e.preventDefault();
      // Send an asynchronous request to the server to perform the logout operation
      fetch('/logout', {
        method: 'POST', // You can use the appropriate HTTP method
        // Add any required headers or credentials
      }).then(function (response) {
        // Handle the response
        console.log('User logged out successfully.');
      }).catch(function (error) {
        // Handle any errors
        console.error('An error occurred during logout:', error);
      });
    });
  </script>

While this works about 80% of the time. It doesn’t always work. Biggest issue is that it opens up an alert automatically. Annoying as hell. I just want it to work like my bank … no pop ups. Just log out.

Ya its really annoying the alert. May be u can use sendBeacon method here de doc

<script>
  window.addEventListener('beforeunload', function () {
    var data = JSON.stringify({ message: 'The tab is closing' });
    navigator.sendBeacon('your-server-url', data);
  });
</script>

This should not display any alert.

2 Likes

I have found success! Works 100% of the time and no pop up alerts!

<script>
        window.addEventListener('unload', function () {
          navigator.sendBeacon('/dmxConnect/api/Authentication/Forms/logout.php', ''); 
        });
</script>

I’m very happy! :beers:

5 Likes

For curiosity, have you checked how your bank does it? (if it's exclusively cookie-based or if it has navigator.sendBeacon)

P.S.: Interesting about navigator.sendBeacon! First time I hear of it

Not sure. I don’t even know how I would find out how a bank does it. I imagine they have pretty good security. My final solution did get me the exact result I was looking for though.

Me neither. ChatGPT to the rescue :wink: