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

javascript - Redirect to main page when user confirms refresh in React JS - Stack Overflow

programmeradmin4浏览0评论

How can I redirect the user to the main page when the user click on this green confirm button (it's in french btw) :

I already have this in the app.js main component but when I try to use the useNavigate() with the navigate function it doesn't work in the "handleBeforeUnload". I also tried window.location.href = "/" but still doesn't work. Also, it's a multiplayer game so I use socket.js to connect the client to a server (I don't know if it changes anything, maybe it helps)

const handleBeforeUnload = (event) => {
        event.preventDefault();
        event.returnValue = ""; // Affiche une confirmation
    };

    useEffect(() => {
        window.addEventListener("beforeunload", handleBeforeUnload)

        return () => {
            window.removeEventListener("beforeunload", handleBeforeUnload)
        }
    }, [])

How can I redirect the user to the main page when the user click on this green confirm button (it's in french btw) :

I already have this in the app.js main component but when I try to use the useNavigate() with the navigate function it doesn't work in the "handleBeforeUnload". I also tried window.location.href = "/" but still doesn't work. Also, it's a multiplayer game so I use socket.js to connect the client to a server (I don't know if it changes anything, maybe it helps)

const handleBeforeUnload = (event) => {
        event.preventDefault();
        event.returnValue = ""; // Affiche une confirmation
    };

    useEffect(() => {
        window.addEventListener("beforeunload", handleBeforeUnload)

        return () => {
            window.removeEventListener("beforeunload", handleBeforeUnload)
        }
    }, [])
Share Improve this question asked Feb 16 at 10:35 GuizmoUGuizmoU 395 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

According to MDN: The beforeunload event is fired when the current window, contained document, and associated resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

If the user wants to close or refresh the tab, window, or browser, preventing that from happening would be annoying for users. This is because is no way to prevent users from doing this.

发布评论

评论列表(0)

  1. 暂无评论