Web browsers enable users to go back to the previous page while browsing the internet by clicking on the back button. But sometimes, you need to prevent the user from visiting the previous page.

You might want to disable the browser’s back button but you can’t disable the functionality through the code in the web page. The only thing here can be done is to prevent a user from going back.

Preventing the user from going back using the back button

The following code needs to be placed in the head section of the web page where you want to prevent the user from going back. You can put this code in a master file if you want to apply it to all pages in your application.

<script type = "text/javascript" >
    function DisableBackButton() {
        window.history.forward();
    }
setTimeout("DisableBackButton()", 0);
window.onunload = function() {
    null
}; 
</script>

Example:

Let’s say you create two pages – index and dashboard. After the index page the user is sent to the dashboard and using the above code, he will be prevented from going back to the index page.

Index Page

The index page has a hyperlink to the Dashboard page.

<h3>Home</h3>
<a href="dashboard.html">Go to Dashboard</a>

Dashboard Page

This page will have the JavaScript code to prevent the user from going back to the index page.

<html>
   <head>
      <script type="text/javascript">
         function DisableBackButton() { window.history.forward(); }
         setTimeout("DisableBackButton()", 0);
         window.onunload = function () { null };
      </script>
   </head>
   <body>
      <h3>Dashobard of the user</h3>
      <hr />
      <a href = "index.html">The previous page.</a>
   </body>
</html>

Related Articles

 

 

Last modified: September 28, 2019

Comments

Write a Reply or Comment

Your email address will not be published.