How can I stop the browser back button using JavaScript?

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

    Very simple and clean function to break the back arrow without interfering with the page afterward.

    Benefits:

    • Loads instantaneously and restores original hash, so the user isn't distracted by URL visibly changing.
    • The user can still exit by pressing back 10 times (that's a good thing) but not accidentally
    • No user interference like other solutions using onbeforeunload
    • It only runs once and doesn't interfere with further hash manipulations in case you use that to track state
    • Restores original hash, so almost invisible.
    • Uses setInterval so it doesn't break slow browsers and always works.
    • Pure Javascript, does not require HTML5 history, works everywhere.
    • Unobrusive, simple, and plays well with other code.
    • Does not use unbeforeunload which interrupts user with modal dialog.
    • It just works without fuss.

    Note: some of the other solutions use onbeforeunload. Please do not use onbeforeunload for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals like onbeforeunload are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.

    How It Works

    1. Executes on page load
    2. Saves your original hash (if one is in the URL).
    3. Sequentially appends #/noop/{1..10} to the hash
    4. Restores the original hash

    That's it. No further messing around, no background event monitoring, nothing else.

    Use It In One Second

    To deploy, just add this anywhere on your page or in your JS:

    
    

提交回复
热议问题