How can I stop the browser back button using JavaScript?

前端 未结 30 3301
没有蜡笔的小新
没有蜡笔的小新 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:59

    ReactJS

    For modal component in ReactJS project, the open or close of the modal, controlling browser back is a necessary action.

    • The stopBrowserBack: the stop of the browser back button functionality, also get a callback function. this callback function is what you want to do:

      const stopBrowserBack = callback => {
        window.history.pushState(null, "", window.location.href);
        window.onpopstate = () => {
          window.history.pushState(null, "", window.location.href);
          callback();
        };
      };
      
    • The startBrowserBack: the revival of the browser back button functionality:

      const startBrowserBack = () => {
        window.onpopstate = undefined;
        window.history.back();
      };
      

    The usage in your project:

    handleOpenModal = () =>
      this.setState(
        { modalOpen: true },
        () => stopBrowserBack(this.handleCloseModal)
      );
    
    handleCloseModal = () =>
      this.setState(
        { modalOpen: false },
        startBrowserBack
      );
    

提交回复
热议问题