Wednesday, July 5, 2017

How to disable browser back behavior with javascript

in certain scenario, we might want to disable the browser back behavior.
eg,
in an ajax application, the application screens changed, but the browser url remains unchanged.
if the user click on the browser back button now
the application is navigate away from what the user doing,
where the user simply wants to navigate to the previous screen.
thus, disable the browser back behavior is very important here.


the solution is simple, just add the following javascript into the <head /> section of the html page.

<head>
  <script>

(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); 

  </script> 
</head>

source:
https://stackoverflow.com/questions/12381563/how-to-stop-browser-back-button-using-javascript


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...