How can I stop the browser back button using JavaScript?

前端 未结 30 3241
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:07

I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.

I have tried the following script, but it stops my timer.

30条回答
  •  感情败类
    2020-11-22 00:46

    Some of the solutions here will not prevent a back event from occurring - they let a back event happen (and data held about the page in the browsers memory is lost) and then they play a forward event to try and hide the fact that a back event just happened. Which is unsuccessful if the page held transient state.

    I wrote this solution for React (when react router is not being used), which is based on vrfvr's answer.

    It will truly stop the back button from doing anything unless the user confirms a popup:

      const onHashChange = useCallback(() => {
        const confirm = window.confirm(
          'Warning - going back will cause you to loose unsaved data. Really go back?',
        );
        window.removeEventListener('hashchange', onHashChange);
        if (confirm) {
          setTimeout(() => {
            window.history.go(-1);
          }, 1);
        } else {
          window.location.hash = 'no-back';
          setTimeout(() => {
            window.addEventListener('hashchange', onHashChange);
          }, 1);
        }
      }, []);
    
      useEffect(() => {
        window.location.hash = 'no-back';
        setTimeout(() => {
          window.addEventListener('hashchange', onHashChange);
        }, 1);
        return () => {
          window.removeEventListener('hashchange', onHashChange);
        };
      }, []);
    

提交回复
热议问题