Skip to content Skip to sidebar Skip to footer

Disable Browsers' Back Button, Completely

Need to prevent users going to the previous page, completely. When I use the following code it works but it's not what I need exactly. When pressing the back button it says 'Docume

Solution 1:

I am not entirely sure if this will work, but you can try handling the event with javascript.

Like if you want to entirely disable the backspace button from allowing users to go back you can do like

$(window).on("keypress", function (e){
    if(e.keycode == "backspace") 
         e.preventDefault();
})

I could figure out the keycode for backspace for you , but that isn't too hard to figure out. Also this uses jquery, but you can use just raw javascript. just wasn't sure what it would be offhand.


Solution 2:

I'm using a slightly different solution:

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

Solution 3:

Based on your post it sounds like your only issue is disabling the backspace button from allowing the user to go back.

Here's what I do for that using jquery. Still allows backspace to work inside enabled text editing inputs, where it should.

    // Prevent the backspace key from navigating back.
    $(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.tagName.toUpperCase() === 'TEXTAREA') {
                doPrevent = d.readOnly || d.disabled;
            }
            else {
                doPrevent = true;
            }
        }

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

Solution 4:

Simplest thing ever:

window.onhashchange = function (event) {
 //blah blah blah
 event.preventDefault();
 return false;
}

You can handle the location domain etc from that (window.location) then cancel the event if you want in this case.

How to Detect Browser Back Button event - Cross Browser


Solution 5:

To disable the back button in the browser you can use use the following code in your JavaScript on the page on which you want to disable the back button.

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

Post a Comment for "Disable Browsers' Back Button, Completely"