2

I have following code in my App.js. What I want to do is log out the user when the window is closed.

componentDidMount() {
    if(localStorage.getItem("currentUser") !== null)
    {
      let currentUser = localStorage.getItem("currentUser");
      this.setState({currentUser:JSON.parse(currentUser)});
    }

    window.addEventListener("beforeunload", this.unload);
  }

unload = (e) => {
    console.log('unload...')
    localStorage.clear();
  }

localStorage is cleared and user is logged out when the windows is closed, but the same seems to happen when the page is refreshed (although the console.log is not executed). Can I stop firing unload() method on page refresh? Is there a better way to logout (clear localStorage) when the browser window is closed? sessionStorage is not an option as it is cleared on tab close. Thanks.

Edit: As Mohit pointed out I tried adding event listener inside componentWillUnmount(), and the user was not logged out on window close.

Asela
  • 303
  • 1
  • 5
  • 16
  • 1
    Why did you registered event inside componentDidMount() ? Can't you register it inside componentWillUnmount? https://reactjs.org/docs/react-component.html#componentwillunmount – Mohit Jul 04 '20 at 06:45
  • @Mohit thanks for looking into this. I tried that, but unload() method did not seem to fire when the window was closed. User was not logged out when I reopened the window. – Asela Jul 04 '20 at 06:50
  • 1
    That's the expected behavior for the `beforeunload` event. `componentWillUnmount` will not work for registering any event listener when the window is closed. You may take a look [here](https://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions) and [here](https://stackoverflow.com/questions/17026464/differentiate-browser-refresh-and-browser-close) for possible solutions – hotpink Jul 04 '20 at 06:57
  • 1
    consider using window.onbeforeunload – Mohit Jul 04 '20 at 07:03
  • 1
    set a local storage variable with a ```ttl```. Check the ttl on ```Load``` then you can find page refreshed or window closed and opened again. Normal human can't close/open window like a refresh, but a crazy one? i don't know!:) – Vahid Alimohamadi Jul 04 '20 at 07:04

1 Answers1

0

Thanks to comments, found a workaround with cookies. When the user logs in, add a cookie,

this.setState({currentUser:JSON.parse(localStorage.getItem("currentUser"))});
document.cookie = "userLoggedIn=true";

And modified componentDidMount() as follows,

componentDidMount() {
    var c = this.getCookie("userLoggedIn");

    if(localStorage.getItem("currentUser") !== null && c == "true")
    {
      let currentUser = localStorage.getItem("currentUser");
      this.setState({currentUser:JSON.parse(currentUser)});
    }
}

getCookie() from https://www.w3schools.com/js/js_cookies.asp

If the window was closed, cookie won't be there. No need for any events like 'beforeunload'

Asela
  • 303
  • 1
  • 5
  • 16