Block Browser Back Button using Client Side Script

***Recommended: It is not recommended to change the default behavior for the browser using client-side¬†scripting languages. They are limited in their approach. But it doesn’t mean that its impossible. There is always a way¬†to accomplish. I found a useful script that handles it in

  • Internet Explorer
  • FireFox
  • Safari
  • Chrome

I didn’t check on any other browser.


<script type="text/javascript">

(function (global) {

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

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

// a glitch (^__^)
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 textboxes 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);

Credentials to StackOverFlow by Rohit

Leave a Reply

Your email address will not be published. Required fields are marked *