• Post category:JavaScript
  • Reading time:3 mins read

We’ll teach you how to use JavaScript to restrict or disable the browser back button in this brief tutorial.

For security reasons, we sometimes need to restrict the user from returning to the previous page. As a result, we can easily disable the back button using JavaScript.

The back button in a browser can be disabled in a variety of ways. In this tutorial, we’ll show you how to use JavaScript to disable the back button.

You may place the code on the first or previous page so that the browser will redirect to the same page if a user attempts to go back to the prior page.

Add the following code to the page’s head section to do this.

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

Example

We’ll make two pages for demonstration purposes: Login and Home. The user will be redirected to the Home page after logging in, and clicking the back button on the browser will prevent the user from returning to the login page from the home page.

We’ll start by creating a login.html file and adding the following code to it.

login.html
<!DOCTYPE html>
<html>

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

<body>
    <h3>Login Page - Code Premix</h3>
    <p>Click here to redirect to the <a href="home.html">Home Page</a></p>
</body>

</html>

The anchor link to redirect on the Home page has been added to the above code. We’ll now create a home.html file and add the following code to it.

home.html
<!DOCTYPE html>
<html>

<head>
    <title>Home</title>
</head>

<body>
    <h3>Home Page - Code Premix</h3>
    <p>On this page, back button functionality is disabled.</p>
</body>

</html>

Output

Run the demo and look at the results in your browser. You will no longer navigate back to the login page from the main page.

That’s all I’ve got for today.
Thank you for reading.

Leave a Reply