4

I have been following from this blog, so far the my custom modal works when i click to another route/link.

The only problem of this implementation is that, the custom modal does not work when I refresh, instead it pops out the built-in confirm alert.

I have here my custom modal.

const CustomConfirm = ({ content, title, isBlocked }) => {
  
  // some codes here (from the blog)
  
  return (
    <>
      <Prompt when message={handleBlockedRoute} />
      {isModalOpen && (
        <ConfirmationModal
          showConfirmationModal={true}
          setShowConfirmationModal={(value) => console.log(value)}
          message={title}
          handleOk={handleConfirmNavigationClick}
          handleCancel={closeModal}
        />
      )}
    </>
  );
};

export default CustomConfirm;

Can we possibly pop out a custom modal before refresh occur?

schutte
  • 1,949
  • 7
  • 25
  • 45

2 Answers2

4

If the user refreshes the page (refresh as in Ctrl+r) or tries to close a tab (as in leave the page) we cannot intercept and prevent those events from happening, thankfully.

Think of how annoying and horrible advertisements would be (like they were!) if that was allowed by the browser.


It's not possible to hijack the onbeforeunload event; How can I override the OnBeforeUnload dialog and replace it with my own?

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Joel Peltonen
  • 13,025
  • 6
  • 64
  • 100
  • actually the current implementation prevents refresh/closing. My problem is, it does not use the custom modal, instead it uses the built-in `confirm` alert – schutte Jun 30 '21 at 06:51
  • 1
    That is straight up not possible to do without using the built-in confirm (to combat popups and for security, Obviously a page should never ever be allowed to stop the user from leaving). MDN: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload HTML Spec: https://html.spec.whatwg.org/multipage/indices.html#event-beforeunload @gecko – Joel Peltonen Jun 30 '21 at 06:58
-2

In componentWillUnmount method make isModalOpen = true.

useEffect(() => {

    return () => // set isModalOpen to true;

}, []);
Joel Peltonen
  • 13,025
  • 6
  • 64
  • 100
Avani Bataviya
  • 750
  • 1
  • 6
  • 20