I have a simple code preventing a page with a form from closing when the form filling is started but isn't finished. Unfortunately, when a user tries to move to the previous page with the browser's button (usually an arrow in the top-left corner of the browser's window) the URL is changed regardless of user's choise to left the page or to stay on the page.
const onRouteChangeStart = useCallback(() => {
if (
(checkConditions &&
!window.confirm("Do you want to exit without saving changes?")
) {
// Prevent navigation
router.events.emit("routeChangeError");
throw "Route change aborted.";
}
}, [usedMetric, editedMetric, fullMetricState, router.events]);
useEffect(() => {
router.events.on("routeChangeStart", onRouteChangeStart);
return () => {
router.events.off("routeChangeStart", onRouteChangeStart);
};
}, [onRouteChangeStart, router.events]);
I tried to use router.push
inside the onRouteChangeStart
event handler to return the current page's URL after the URL is changed. It worked but turned history into a mess because two changes of URL (to the previous page's URL and then to the current page's URL) were saved in the history.
Also I tried to change window.location
inside onRouteChangeStart
but as expected it was even worse thatn router.push
because it triggered the handler infinitely.
Can i prevent going to the previous page (or the next page - it has the same problem) without any effects on history and URL?