There are numerous different ways of disabling the back button or at least messing with the working of the back button so that the browsers cannot go to the previous page. However, fully disabling the browser’s back button is not a good option, plus client-side applications don’t have that many privileges or rights to do so due to security reasons.
The window.history.forward() Method
In this article, we will stop the normal working of the back button of the web browser by using the window Object. And to be precise, we will head inside the window object’s history and move it “forward” when the browser tries to revisit the previous page.
Demonstration of Window.history.forward() Method
To start, we need two different HTML pages. The first page is called the home.html, and it contains the following lines:
<a href="secondPage.html">Click me to visit the next page</a>
As you can see, we are simply creating an <a> in which we are simply referring to the secondPage.html.
After that, simply create the second HTML with the exact name secondPage.html. And in this HTML document, you want to add the following lines:
<b>This is the second page</b>
This second page only contains text that tells the user that this is the second page. Running the home webpage will give the following result on the browser:
As you can see, clicking the link takes us to the second page, and from the second page, you can press the back button to again come to the home.html
Now in the home.html document, you are going to add in the following script lines inside the script tag:
In these lines, we are accessing the history of the browser’s window object and then calling the forward() method to move the browser back to the second page. Thus messing with the normal flow of the back button of the browser.
This script will only work when history has some onward entry to go to. This means that the first-time loading of the webpage will never be affected by this.
After this, simply open the home webpage, click the link to go to the second webpage, and then try clicking the back button of the browser, and you will get the following output:
As you can see, clicking the back button on the browser’s doesn’t take us back to the home.html rather it takes us again on the secondPage.html