Show alert dialog when closing browser tab (using beforeunload)

111 Views Asked by At

I am looking to show an alert box when closing the browser tab.

I did look through several examples, but I am unable to get it working. Sharing my codesandbox.

It generates a link to a tab where the application can be opened in its own page such as https://vqjggc.csb.app/

When closing the tab using the X button or Ctrl+w, my expectation was that it would show a dialog, but it doesn't seem to.

Please advise what I am doing wrong. I have tried on both Chrome (Version 116.0.5845.141 (Official Build) (64-bit)) as well as Edge (Version 116.0.1938.69 (Official build) (64-bit))

Attached a gif of what I observe when opening the app using the above link and hitting Ctrl+w.enter image description here

1

There are 1 best solutions below

1
yassine-eluharani On

When the component unmounts, the cleanup function will be executed. In this case, the cleanup function removes the event listener for the "beforeunload" event.

  useEffect(() => {
    const handleBeforeUnload = (event) => {
      event.preventDefault();
      event.returnValue = "";
    };
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);