0

Hello, I am working on nextJs project, there is a unique requirement when the user goes to close the browser tab that time needs to open some other popup, but there is one problem when I click on to tab close button first default shows me this alert then I click to cancel then its show my popup, the requirement is open only my popup(i don't want change alert box message, just need to off alert box.), please help me if anyone knows solution Thank you.

My Popup is not an alert box, its an HTML and CSS.

enter image description here

  const [openPopUp, setOpenPopUp] = useState(false);

  const onBackButtonEvent = (e) => {
    e.preventDefault();
    setOpenPopUp(true)
    e.returnValue = "";
    return ""
  }
  
  useEffect(() => {
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', onBackButtonEvent);
    window.addEventListener('beforeunload', onBackButtonEvent);
    window.alert = function() { }; 
    return () => {
      window.removeEventListener('popstate', onBackButtonEvent);
      window.removeEventListener('beforeunload', onBackButtonEvent);
    };
  }, []);

Brijesh Kalkani
  • 789
  • 10
  • 27
  • 2
    Does this answer your question? [Is it possible to display a custom message in the beforeunload popup?](https://stackoverflow.com/questions/38879742/is-it-possible-to-display-a-custom-message-in-the-beforeunload-popup) Impossible to do – Konrad Jun 20 '23 at 16:25
  • @Konrad my custom popup is not an alert box, its an HTML and CSS. – Brijesh Kalkani Jun 20 '23 at 16:31
  • It's even worse. You still can't do that – Konrad Jun 20 '23 at 16:32
  • You can not replace the beforeunload pop up. So your task is not possible. – epascarello Jun 20 '23 at 16:42
  • 1
    You can't "do" anything in the `beforeunload` event. It can only be used to trigger the browser-dialog for confirming or cancelling the page unload, through a call to `evt.preventDefault()`. – Mike 'Pomax' Kamermans Jun 20 '23 at 16:42
  • (And of course, using this event stops the page from being added to the back/forward cache, so it makes history navigation quite a lot slower. You basically don't want to use this event at all. In a React app, just assume users will close tabs, and let them because you're constantly saving or syncing anything that needs saving or syncing) – Mike 'Pomax' Kamermans Jun 20 '23 at 16:49

0 Answers0