How to disable the browser back button navigation using javascript

Hi, Today you will learn about "How to disable the browser back button navigation using javascript", In general, we don't use this type of requirement in the project.But is very useful in so many situations.

For example, we are doing in the online cart i.e an e-commerce platform so here after the placing the order and once the user checks out the order in his cart and payment completed it will redirect and shown the order success page after that user doesn't go back to the previous pages. So here we want to block the browser back button navigation.

So here in this situation we will use this code. if you searched on the internet you will find the code i.e
<script type="text/javascript">  
     window.history.forward();  
     function noBack()  
     {  
       window.history.forward();  
     }  
 </script>  
 <body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">   
This code is not working properly. so I have found the solution to this problem. Just add the below script code on the file where the user doesn't go back from that file.
<script type="text/javascript">  
 (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>  
Here you can check the demo.
Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff


EmoticonEmoticon