Looking to implement a feature that prevents changing the URL from my component. The goal is to display a message and allow users to choose between canceling (no change to URL) or confirming (change the URL). How can I achieve this in the upcoming 13.4 version?
I have tried implementing the following logic, but it seems to not be functioning as expected. The window.confirm message does not appear.
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);
};