Log the user out if the browser is closed

Hello,
I want to log the user out when he closes a tab (or browser). If he has another tab already opened, it should be logged out too.

This is what I’ve tried:

  1. Create a JavaScripttoBubble element with name LogOut and enable ‘Trigger Event’ flag.
  2. On Page Load, run this javascript in header (which is used in every page)
window.addEventListener('beforeunload', function (e) {
  bubble_fn_LogOut()
});
  1. Create a JavaScript to Bubble event for the above created element, and add the log out action.

What happens is, when the user logs in, it automatically gets logged out. Does the JS event listener ‘beforeunload’ gets called even a page redirect happens? Please correct my process or any alternate solution.

Thanks in advance!

The issue is is that the ‘beforeunload’ event is being fired on page loadwhich is causing the user to get logged out immediately. This is because the event is not specific to tab closures or browser quits; it’s triggered whenever the user navigates away from the page.
To fix that you need to prevent the 'beforeunload event from being called on page load

Thanks Siddharth. I tried using ‘unload’ event listener too and it’s also behaving the same way. How do I prevent ‘beforeunload’ from being called on page load? Is there any other event listener which only gets triggered on browser/tab close?

Thanks in advance!

I think due to the placement of the beforeunload event listener within the page load script, When the page loads . beforeunload event is triggered even though the user hasn’t actually interacted with the page yet causing in the logout action being executed immediately causing the user to be logged out as soon as they log in.
you should move the beforeunload event listener outside of the page load script and into a separate script that only executes when the user is actually closing the tab or browser, now the logout action will only be triggered when the user has genuinely decided to leave the session,

This topic was automatically closed after 70 days. New replies are no longer allowed.