1

I am trying to detect browser tab / browser close event with react js to detect user log out action (call api). I have tried using beforeunload event as

  useEffect(() => {
    window.addEventListener("beforeunload", function(e) {

      let confirmationMessage = "o/";

      (e || window.event).returnValue = confirmationMessage; //Gecko + IE

      console.log("logout !");
      return confirmationMessage; //Webkit, Safari, Chrome
    
    });
  });

It works fine if user closes the tab but the issue is it is also firing when user reload the page which I dont want for log out action, I've tried searching and tried these solutions as well but no work for me. Are there any solutions to detect only when browser / browser tab closes and not reload ?

Detect browser close event

https://stackoverflow.com/a/5593734/11866037

Warn user before leaving web page with unsaved changes

Kaung Khant Zaw
  • 1,508
  • 3
  • 19
  • 31

1 Answers1

2

you missed to add the return function in your useEffect which runs the cleanup i.e componentWillUnmount.

Your code will look something like this:

useEffect(() => {
    return () => {

       window.addEventListener("beforeunload", function(e) {

      let confirmationMessage = "o/";

      (e || window.event).returnValue = confirmationMessage; //Gecko + IE

      console.log("logout !");
      return confirmationMessage; //Webkit, Safari, Chrome
    
    });
   }
   
  });
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103