javascriptreactjsbrowseronbeforeunload

React - check when tab or browser is closed, but not on refresh


I want to disconnect all my users when the tab is closing or the browser is getting closed, so far so good. But when I refresh the page, all my users get disconnected too, this should not happen on refresh. Is it possible to avoid to execute this event on refresh? I saw some users doing with localStorage, but I still didn't get the point.

componentDidMount() {
  this.beforeUnloadListener();
}


beforeUnloadListener = () => {
  window.addEventListener("beforeunload", (ev) => {
    ev.preventDefault();
    // code to logout user
  });
};

Solution

  • The way beforeunload works, you can not differentiate weather it's a page refresh or a browser close. beforeunload it is a quite confusing event avoid using this.

    Hence for cases where you are dealing with the session you should use session storage. The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).