最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I prevent the Next router from pushing back in history without any effects? - Stack Overflow

programmeradmin2浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论