how to stop browser back button using javascript

2018-12-31 04:06发布

I am doing online quiz app in php. I want to restrict user while going back in exam. I have tried following script but it stops my timer. What should I do please suggest me. I have included source code. The timer is stored in cdtimer.js

<script type="text/javascript">
        window.history.forward();
        function noBack()
        {
            window.history.forward();
        }
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">

I have exam timer which takes duration of exam from mysql db and starts timer accordingly it stops when I put code for disabling back button. what will be the problem.

21条回答
残风、尘缘若梦
2楼-- · 2018-12-31 04:46

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:

<script>
/* break back button */                                                                        
window.onload=function(){                                                                      
  var i=0; var previous_hash = window.location.hash;                                           
  var x = setInterval(function(){                                                              
    i++; window.location.hash = "/noop/" + i;                                                  
    if (i==10){clearInterval(x);                                                               
      window.location.hash = previous_hash;}                                                   
  },10);
}
</script>
查看更多
闭嘴吧你
3楼-- · 2018-12-31 04:47

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'
    }
  }
}
查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 04:48
<script language="JavaScript">
    javascript:window.history.forward(1);
</script>
查看更多
倾城一夜雪
5楼-- · 2018-12-31 04:55

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');
});
查看更多
情到深处是孤独
6楼-- · 2018-12-31 04:55

This is the way I could it accomplish it. Weirdly changing the window.location didn't worked out fine in chrome and safari. Happens that the location.hash doesn't create an entry in the history for chrome and safari. So you will have to use the pushstate. This is working for me in all browsers.

    history.pushState({ page: 1 }, "title 1", "#nbb");
    window.onhashchange = function (event) {
        window.location.hash = "nbb";

    };
查看更多
浪荡孟婆
7楼-- · 2018-12-31 04:57

This seems to have worked for us in disabling the back button on the browser, as well as the backspace button taking you back.

history.pushState(null, null, $(location).attr('href'));
    window.addEventListener('popstate', function () {
        history.pushState(null, null, $(location).attr('href'));
    });
查看更多
登录 后发表回答