0

In my Application i want to detect Browser or Tab close event and then for this event would like to submit form for logout function and clear user session.

I have tried window.onbeforeunload event but it is fire for all even i click link or refresh page.

Any one can please help me.

2 Answers2

1

There is no specific API to achieve what you want.

What you can do is the following:

  1. Issue access/session tokens with (relatively) short lifespans (like 1 minute)
  2. Have your frontend "continuously" refresh the tokens to keep the application signed in

In this way after a (relatively) small delay if the frontend is not running you end up with an expired session/access token and the user is effectively logged out.

Cons of this approach: if the user has a small window of connectivity problems their session will expire. If your system is a mobile application this might make your App very frustrating to use in various circumstances. Might not be a big problem if your use case is access from workstations.

GACy20
  • 949
  • 1
  • 6
  • 14
  • No my frontend didnot "continuously" refresh the tokens – namrata mahajan Apr 12 '22 at 12:05
  • @namratamahajan Yeah... that's what I was saying. You can modify your code so that it refreshes the authentication tokens frequently. In this way you can reduce the time between when a tab is closed and when the session times out. Obviously the shorter the session time the higher the chances of expiring by accident. – GACy20 Apr 12 '22 at 15:26
-1

You cannot detect a browser/tab close event natively in JavaScript. When the user closes a tab, all the script running on the page effectively ceases executing and no javascript code can run after that.

Krissh
  • 67
  • 1
  • 7