How can I stop the browser back button using JavaScript?

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

        history.pushState(null, null, location.href);
        window.onpopstate = function () {
            history.go(1);
        };
    

    0 讨论(0)
  • 2020-11-22 01:08

    You can just put a small script and then check. It won't allow you to visit previous page.

    This is done in JavaScript.

    <script type="text/javascript">
        function preventbackbutton() { window.history.forward(); }
        setTimeout("preventbackbutton()", 0);
        window.onunload = function () { null };
    </script>
    

    The window.onunload function fires when you try to visit back or previous page through browser.

    0 讨论(0)
  • 2020-11-22 01:09

    There are numerous reasons why disabling the back button will not really work. Your best bet is to warn the user:

    window.onbeforeunload = function() { return "Your work will be lost."; };
    

    This page does list a number of ways you could try to disable the back button, but none are guaranteed:

    http://www.irt.org/script/311.htm

    0 讨论(0)
  • 2020-11-22 01:11

    This code will disable the back button for modern browsers which support the HTML5 History API. Under normal circumstances, pushing the back button goes back one step, to the previous page. If you use history.pushState(), you start adding extra sub-steps to the current page. The way it works is, if you were to use history.pushState() three times, then start pushing the back button, the first three times it would navigate back in these sub-steps, and then the fourth time it would go back to the previous page.

    If you combine this behaviour with an event listener on the popstate event, you can essentially set up an infinite loop of sub-states. So, you load the page, push a sub-state, then hit the back button, which pops a sub-state and also pushes another one, so if you push the back button again it will never run out of sub-states to push. If you feel that it's necessary to disable the back button, this will get you there.

    history.pushState(null, null, 'no-back-button');
    window.addEventListener('popstate', function(event) {
      history.pushState(null, null, 'no-back-button');
    });
    
    0 讨论(0)
  • 2020-11-22 01:11

    This article on jordanhollinger.com is the best option I feel. Similar to Razor's answer but a bit clearer. Code below; full credits to Jordan Hollinger:

    Page before:

    <a href="/page-of-no-return.htm#no-back>You can't go back from the next page</a>
    

    Page of no return's JavaScript:

    // It works without the History API, but will clutter up the history
    var history_api = typeof history.pushState !== 'undefined'
    
    // The previous page asks that it not be returned to
    if ( location.hash == '#no-back' ) {
      // Push "#no-back" onto the history, making it the most recent "page"
      if ( history_api ) history.pushState(null, '', '#stay')
      else location.hash = '#stay'
    
      // When the back button is pressed, it will harmlessly change the url
      // hash from "#stay" to "#no-back", which triggers this function
      window.onhashchange = function() {
        // User tried to go back; warn user, rinse and repeat
        if ( location.hash == '#no-back' ) {
          alert("You shall not pass!")
          if ( history_api ) history.pushState(null, '', '#stay')
          else location.hash = '#stay'
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 01:12

    I came across this, needing a solution which worked correctly and "nicely" on a variety of browsers, including Mobile Safari (iOS9 at time of posting). None of the solutions were quite right. I offer the following (tested on IE11, FireFox, Chrome & Safari):

    history.pushState(null, document.title, location.href);
    window.addEventListener('popstate', function (event)
    {
      history.pushState(null, document.title, location.href);
    });
    

    Note the following:

    • history.forward() (my old solution) does not work on Mobile Safari --- it seems to do nothing (i.e. the user can still go back). history.pushState() does work on all of them.
    • the 3rd argument to history.pushState() is a url. Solutions which pass a string like 'no-back-button' or 'pagename' seem to work OK, until you then try a Refresh/Reload on the page, at which point a "Page not found" error is generated when the browser tries to locate a page with that as its Url. (The browser is also likely to include that string in the address bar when on the page, which is ugly.) location.href should be used for the Url.
    • the 2nd argument to history.pushState() is a title. Looking around the web most places say it is "not used", and all the solutions here pass null for that. However, in Mobile Safari at least, that puts the page's Url into the history dropdown the user can access. But when it adds an entry for a page visit normally, it puts in its title, which is preferable. So passing document.title for that results in the same behaviour.
    0 讨论(0)
提交回复
热议问题