How can I stop the browser back button using JavaScript?

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

    In a modern browser this seems to work:

    // https://developer.mozilla.org/en-US/docs/Web/API/History_API
    let popHandler = () => {
      if (confirm('Go back?')) {
        window.history.back() 
      } else {
        window.history.forward()
        setTimeout(() => {
          window.addEventListener('popstate', popHandler, {once: true})
        }, 50) // delay needed since the above is an async operation for some reason
      }
    }
    window.addEventListener('popstate', popHandler, {once: true})
    window.history.pushState(null,null,null)
    

提交回复
热议问题