How do I prevent navigation to the previous page when users press the window's back button?

28 Views Asked by At

I am trying to do it with event.preventdefault() on the event popstate.

    useEffect(() => {
        let isOnce = false;
        const handlePop = (update: Update) => {
            if (usernameToSend && !isOnce && update.action === 'POP') {
                window.addEventListener("popstate", function(event) {
                    event.preventDefault();
                    if (window.confirm("Leaving so soon? Chat data will be lost.")) {
                        isOnce = true;
                        exitToServer();
                    }
                    else {
                        history.back();
                    }
                });
            }
            else {
                isOnce = false;
            }
        };
        if (!isOnce) {
            history.listen(handlePop);
        }

    }, [usernameToSend]);
    

How do I link update.action 'POP' with event.preventDefault()?
Do I create a second parameter event after the update parameter like this?

const handlePop = (update: Update, event) => {
0

There are 0 best solutions below