Manju Manju - 3 months ago 18
Javascript Question

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser using Javascript and not using Jquery Mobile library.

Solution would be really appreciated. I tried with few solutions online, but nothing seemed to work.

Answer

You should never do that. https://www.irt.org/script/311.htm By the way, you may just warn the user using window.onbeforeunload.

You can-not actually disable browser back button. And there is no event for capturing the back button click. If it is really necessary you can do something like that:

(function (global) { 
    var _extra_hash = "!";
    var noBack = function () {
       global.location.href += "#";

       global.setTimeout(function () {
           global.location.href += _extra_hash;
       }, 50);
    };

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

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

       // disables backspace on page except on input fields and textarea..
       // this is disabling backspace

       /*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);

But the user can still kill the tab. Anyway, It is generally a bad idea overriding the default behavior of web browser.

Comments