skip to Main Content

I created a modal if the user click refresh. Now I want to use my created modal instead of the default prompt as seen on the image. I want to show the modal that I created instead of the default prompt.

enter image description here

This is my code:

const [showModal, setShowModal] = useState(false);
const [refreshPage, setRefreshPage] = useState(false);

useEffect(() => {
 const unloadCallback = (event) => {
  event.preventDefault();
  event.returnValue = "";
  setShowModal(true);
}
if (refreshPage) {
  window.location.reload();
} else {
  window.addEventListener("beforeunload", unloadCallback);
}

return () => window.removeEventListener("beforeunload", unloadCallback);
}, [refreshPage])

const handleCloseModal = () => {
 setShowModal(false);
}

const handleRefreshClick = () => {
  setRefreshPage(true);
}

2

Answers


  1. I can suggest this implementation:

    here you can use a custom modal, by replacing the div with a custom component, or by adding some CSS

    feel free then to add the on effect and all you need,
    I don’t have enough informations in your code to provide you a better answer

    import { useState } from 'react';
    
    function YourComponent() {
      const [showModal, setShowModal] = useState(false);
    
      const handleOpenModal = () => {
        setShowModal(true);
      }
    
      const handleCloseModal = () => {
        setShowModal(false);
      }
    
      const handleRefreshClick = () => {
        window.location.reload();
      }
    
      return (
        <div>
          <button onClick={handleOpenModal}>Refresh</button>
    
          {showModal && (
            <div>
              {/* This is your modal code */}
              <p>Are you sure you want to refresh?</p>
              <button onClick={handleRefreshClick}>Yes, Refresh</button>
              <button onClick={handleCloseModal}>Cancel</button>
            </div>
          )}
        </div>
      );
    }
    
    Login or Signup to reply.
  2. As mentioned above, you can’t fully replace the browser’s default "beforeunload". The browser imposes restrictions to prevent potentially malicious behaviour. Specifically, you can’t suppress the browser’s default prompt and show your own UI instead because the beforeunload event doesn’t permit it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search