1

I have a react app and I want to prevent the user refresh the page and ask him if he is sure he wants to refresh the page.

This is my useEffect hook:

  useEffect(() => {

const unloadCallback = (event) => {
  event.preventDefault();
  event.returnValue = "";
  return "";
};

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

The main problem is that I can't edit the default message of the modal that appears on refreshing the page and this event is triggered on closing the tab too.

How can I change the message and stop asking for confirmation on closing the tab or is there a way to add a custom modal from scratch instead using the browser modal?

SnNaCk
  • 2,370
  • 2
  • 5
  • 16
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#compatibility_notes: _"In older browsers, the return value of the event is displayed in this dialog. Since Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage is shown instead of the returned string."_ - so you _can't_ control what message gets shown any more. – CBroe Apr 25 '23 at 06:05
  • 1
    _"and this event is triggered on closing the tab too"_ - of course it is. The point is to help prevent the loss of unsaved data, so if it did _not_ trigger in this scenario, it wouldn't be doing its job. – CBroe Apr 25 '23 at 06:06

0 Answers0