how to stop browser back button using javascript

I am doing an online quiz app 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. What should I do?

I have included the 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 the exam timer which takes a duration for the exam from a mysql value. The timer starts accordingly but it stops when I put the code in for disabling the back button. What is my problem?

Answers:

Answer

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

Answer

It is generally a bad idea overriding the default behavior of web browser. Client side script does not have the sufficient privilege to do this for security reason.

There are few similar questions asked as well,

You can-not actually disable browser back button. However you can do magic using your logic to prevent user from navigating back which will create an impression like it is disabled. Here is how, check out the following snippet.

(function (global) { 

    if(typeof (global) === "undefined") {
        throw new Error("window is undefined");
    }

    var _hash = "!";
    var noBackPlease = function () {
        global.location.href += "#";

        // making sure we have the fruit available for juice (^__^)
        global.setTimeout(function () {
            global.location.href += "!";
        }, 50);
    };

    global.onhashchange = function () {
        if (global.location.hash !== _hash) {
            global.location.hash = _hash;
        }
    };

    global.onload = function () {            
        noBackPlease();

        // disables backspace on page except on input fields and textarea..
        document.body.onkeydown = function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        };          
    }

})(window);

This is in pure JavaScript so it would work in most of the browsers. It would also disable backspace key but key will work normally inside input fields and textarea.

Recommended Setup:

Place this snippet in a separate script and include it on a page where you want this behavior. In current setup it will execute onload event of DOM which is the ideal entry point for this code.

Working DEMO!

Tested and verified in following browsers,

  • Chrome.
  • Firefox.
  • IE (8-11) and Edge.
  • Safari.
Answer
<script>
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
</script> 
Answer

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.
Answer

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');
});
Answer

For Restrict Browser back event

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

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";

    };
Answer

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

Answer
<html>
<head>
    <title>Disable Back Button in Browser - Online Demo</title>
    <style type="text/css">
        body, input {
            font-family: Calibri, Arial;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() {
            window.history.forward();
        }
    </script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <H2>Demo</H2>
    <p>This page contains the code to avoid Back button.</p>
    <p>Click here to Goto <a href="noback.html">NoBack Page</a></p>
</body>
</html>
Answer

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'
    }
  }
}
Answer
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

This javascript does not allow any user to go back (works in Chrome, FF, IE, Edge)

Answer

Try it with ease :

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

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>
Answer

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'));
    });
Answer
   <script src="~/main.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.history.forward();
        function noBack() { window.history.forward(); } </script>
Answer

You simply cannot and should not do this. However, but this might be helpful

<script type = "text/javascript" >
history.pushState(null, null, 'pagename');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'pagename');
});
</script>

Works in my chrome and firefox

Answer

Try this to prevent backspace button in IE which by default act as "Back":

<script language="JavaScript">
$(document).ready(function() {
$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;


    if (event.keyCode === 8 ) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && 
             (
                 d.type.toUpperCase() === 'TEXT' ||
                 d.type.toUpperCase() === 'PASSWORD' || 
                 d.type.toUpperCase() === 'FILE' || 
                 d.type.toUpperCase() === 'EMAIL' || 
                 d.type.toUpperCase() === 'SEARCH' || 
                 d.type.toUpperCase() === 'DATE' )
             ) || 
             d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {

            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }

    try {
        document.addEventListener('keydown', function (e) {
               if ((e.keyCode === 13)){
                  // alert('Enter keydown');
                   e.stopPropagation();
                   e.preventDefault();
               }



           }, true);
        } catch (err) {}
    });
});
</script>
Answer

I believe the perfect yet solution is actually pretty straightforward, which I used for many years now.

It's basically assigning the window's "onbeforeunload" event along with the ongoing document 'mouseenter' / 'mouseleave' events so the alert only triggers when clicks are outside the document scope (which then could be either the back or forward button of the browser)

$(document).on('mouseenter', function(e) { 
        window.onbeforeunload = null; 
    }
);

$(document).on('mouseleave', function(e) { 
        window.onbeforeunload = function() { return "You work will be lost."; };
    }
);
Answer

This code tested with latest Chrome and Firefox browsers.

    <script type="text/javascript">
        history.pushState(null, null, location.href);
        history.back();
        history.forward();
        window.onpopstate = function () { history.go(1); };
    </script>
Answer

I create one HTML page ( index.html ). I also create a one ( mechanism.js ) inside a ( script ) folder / directory. Then, I lay all my content inside of ( index.html ) using form, table, span, and div tags as needed. Now, here's the trick that will make back / forward do nothing!

First, the fact that you have only one page! Second, the use of JavaScript with span / div tags to hide and display content on the same page when needed via regular links!

Inside ' index.html ' :

    <td width="89px" align="right" valign="top" style="letter-spacing:1px;">
     <small>
      <b>
       <a href="#" class="traff" onClick="DisplayInTrafficTable();">IN</a>&nbsp;
      </b>
     </small>
     [&nbsp;<span id="inCountSPN">0</span>&nbsp;]
    </td>

Inside ' mechanism.js ' :

    function DisplayInTrafficTable()
    {
     var itmsCNT = 0;
     var dsplyIn = "";
     for ( i=0; i<inTraffic.length; i++ )
     {
      dsplyIn += "<tr><td width='11'></td><td align='right'>" + (++itmsCNT) + "</td><td width='11'></td><td><b>" + inTraffic[i] + "</b></td><td width='11'></td><td>" + entryTimeArray[i] + "</td><td width='11'></td><td>" + entryDateArray[i] + "</td><td width='11'></td></tr>";
     }
     document.getElementById('inOutSPN').innerHTML = "" +
                                             "<table border='0' style='background:#fff;'><tr><th colspan='21' style='background:#feb;padding:11px;'><h3 style='margin-bottom:-1px;'>INCOMING TRAFFIC REPORT</h3>" + DateStamp() + "&nbsp;&nbsp;-&nbsp;&nbsp;<small><a href='#' style='letter-spacing:1px;' onclick='OpenPrintableIn();'>PRINT</a></small></th></tr><tr style='background:#eee;'><td></td><td><b>###</b></td><td></td><td><b>ID #</b></td><td></td><td width='79'><b>TYPE</b></td><td></td><td><b>FIRST</b></td><td></td><td><b>LAST</b></td><td></td><td><b>PLATE #</b></td><td></td><td><b>COMPANY</b></td><td></td><td><b>TIME</b></td><td></td><td><b>DATE</b></td><td></td><td><b>IN / OUT</b></td><td></td></tr>" + dsplyIn.toUpperCase() + "</table>" +
                                             "";
     return document.getElementById('inOutSPN').innerHTML;
    }

It looks hairy, but note the function names and calls, embedded HTML, and the span tag id calls. This was to show how you can inject different HTML into same span tag on same page! How can Back/Forward affect this design? It cannot, because you are hiding objects and replacing others all on the same page!

How to hide and display? Here goes: Inside functions in ' mechanism.js ' as needed, use:

    document.getElementById('textOverPic').style.display = "none"; //hide
    document.getElementById('textOverPic').style.display = "";     //display

Inside ' index.html ' call functions through links:

    <img src="images/someimage.jpg" alt="" />
    <span class="textOverPic" id="textOverPic"></span>

and

    <a href="#" style="color:#119;font-size:11px;text-decoration:none;letter-spacing:1px;" onclick="HiddenTextsManager(1);">Introduction</a>

I hope I did not give you a headache. Sorry if I did :-)

Answer

In my case this was a shopping order. So what I did was disable the button. When the user clicked back, the button was disabled still. When they clicked back one more time, and then clicked a page button to go forward. I knew their order was submitted and skipped to another page.

In the case when the page actually refreshed which would make the button (theoretically), available; I was then able to react in the page load that the order is already submitted and redirect then too.

Answer
<script language="JavaScript">
    javascript:window.history.forward(1);
</script>
Answer

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)
Answer

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.

Hope this helps.

Answer

None of the most-upvoted answers worked for me in Chrome 79. It looks like Chrome changed its behavior with respect to the Back button after Version 75, see here:

https://support.google.com/chrome/thread/8721521?hl=en

However, in that Google thread, the answer provided by Azrulmukmin Azmi at the very end did work. This is his solution.

<script>

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

</script>

The problem with Chrome is that it doesn't trigger onpopstate event unless you make browser action ( i.e. call history.back). Thats why I've added those to script.

I don't entirely understand what he wrote, but apparently an additional history.back() / history.forward() is now required for blocking Back in Chrome 75+.

Answer
//"use strict";
function stopBackSpace(e) {
    var ev = e || window.event;
    var obj = ev.target || ev.srcElement;
    var t = obj.type || obj.getAttribute('type');

    var vReadOnly = obj.getAttribute('readonly');
    var vEnabled = obj.getAttribute('enabled');
    // null
    vReadOnly = (vReadOnly == null) ? false : vReadOnly;
    vEnabled = (vEnabled == null) ? true : vEnabled;
    // when click Backspace,judge the type of obj.

    var flag1 = ((t == 'password' || t == 'text' || t == 'textarea') && ((vReadOnly == true || vReadOnly == 'readonly') || vEnabled != true)) ? true : false;

    var flag2 = (t != 'password' && t != 'text' && t != 'textarea') ? true : false;

    if (flag2) {
        e.keyCode = 0;
        e.cancelBubble = true;
        return false;
    }
    if (flag1) {
        e.keyCode = 0;
        e.cancelBubble = true;
        return false;
    }
}
if (typeof($) == 'function') {
    $(function() {
        $(document).keydown(function(e) {
            if (e.keyCode == 8) {
                return stopBackSpace(e);
            }
        });
    });
} else {
    document.onkeydown = stopBackSpace;
}
Answer

I had this problem with React.JS. (class component)

And solve easily

componentDidMount(){
   window.addEventListener("popstate", e=> {
      this.props.history.goForward();
   }
}

I've used HashRouter from react-router-dom.

Answer

Just set location.hash="Something", On pressing back button the hash will get removed from url but page won't go back, This method is good for preventing going back accidentally, but for security purposes you should design your backend for preventing re-answering

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.