Show window.confirm for prevent changing the URL

93 views Asked by At

Needs to prevent changing url from my component. So, nees to show a message, and if user choose cancel - don't change the URL, if OK - change the URL. How I can make this logic in next 13.4

It's my current logic, but it doesn't work. I even don't see the window.confirm message

useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const mess = window.confirm('Are you sure you want to leave?');
event.returnValue = mess;
if (!mess) {
event.preventDefault();
       }
     };

window.addEventListener('beforeunload', handleBeforeUnload);

return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
     };

1

There are 1 answers

2
Karo On

This seems to work for me, even when I try in in the StackOverflow snippet.

window.addEventListener('beforeunload', function (event) {
  const unsavedChanges = true;
  if (unsavedChanges) {
    const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
    event.returnValue = confirmationMessage;
    return confirmationMessage; 
  }
});
<button onclick="window.location.href = 'https://example.com/'">Go to example.com</button>
<button onclick="window.location.reload()">Reload</button>