2

I want to implement logout functionality when user closes the tab. I am storing JWT tokens in my local storage which are needed to be cleared every time user closes the tab without clicking the 'Log out' button in my React.js application.

All over the internet, I find 'beforeunload' event being used, but I think it gets fired when we refresh the page or navigate to other page via clicking a link, which is not what I want.

Also, is there a way to find if user closed the tab or the window in JavaScript?

Any help would be appreciated. Thanks.

Aswin K
  • 333
  • 3
  • 12
  • SessionStorage is an alternative to localStorage https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage – Björn May 18 '18 at 13:08
  • 1
    Check out this article, it discusses calling a function on window close. https://stackoverflow.com/questions/13443503/run-javascript-code-on-window-close-or-page-refresh – Bob van 't Padje May 18 '18 at 13:11
  • Thanks for the comment, but all of them talk about using 'beforeunload', but this event fires when you hit the Refresh button on the browser. I don't want to logout a user when they refresh the page. That's not good user experience. – Aswin K May 18 '18 at 17:39
  • 1
    @Björn Thanks for the comment, but I am using local storage because as per our app requirement, we need to allow a user to sign in on multiple tabs and once the user logs out in one tab, he should be automatically logged out of the other tabs. So, we used local storage instead of session storage to have access to JWT tokens across browser tabs. – Aswin K May 18 '18 at 17:41
  • Even I have the same problem. Were you able to fix this issue? – Ankit Kumar Apr 06 '20 at 00:59
  • No, I moved to a different project and I don't know if they ever solved it. sorry. – Aswin K Apr 07 '20 at 12:15

1 Answers1

-1

Try beforeunload event listner

window.addEventListener("beforeunload", function (e) {
  //Log Out Call
}

But it will not work in all browsers.

Midhun G S
  • 906
  • 9
  • 22