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.
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
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
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.