Javascript – Trying to disable the browser’s back button

html5-historyjavascript

I've written two HTML files:

  1. Login.html
    <a href = "Home.html">Next Page</a>
  2. Home.html`
<html>
   <body>
      <a href = >Login.html>>Prev Page</a>
   </body>
<script type = "text/javascript" >

	history.pushState("anything", "", "#1");
    	window.onhashchange = function (event) {
       		window.location.hash = "a";
    	};
</script>
</html>

`
I'm trying to disable browser's back button. If i execute this code on chrome it doesn't disable the back button but if i run history.state command in console of Home.html page and then i click the back button, then it remains on same page(works as expected). Why so?

Best Answer

FOA, Thanks everyone for your answers.

Finally below code gave me the solution:

history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();