Clue Mediator

How to disable the browser back button using JavaScript

📅January 20, 2021

In this short article, we’ll show you how to disable the browser back button using JavaScript.

Sometimes we need to prevent the user from going back to the previous page for security. So we can easily restrict the back button using JavaScript.

There are many ways to disable the back button in the browser. Here, we'll explain a simple way to stop the back button using JavaScript.

You can add the code on the first or previous page so that when a user tries to redirect on the previous page, the browser will redirect to the same page.

To do this, you need to add the following code to the head section of the page.

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

Example

For demo purposes, we will create two pages `Login` and `Home`. After login, the user will be redirected to the Home page, and using the browser back button will prevent it from returning to the login page from the home page.

First, we will create a `login.html` file and write the following code.

login.html





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



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

In the above code, we have added the anchor link to redirect on the Home page. Now, we will create a `home.html` file and write the following code.

home.html





    <title>Home</title>



    <h3>Home Page - Clue Mediator</h3>
    <p>On this page, back button functionality is disabled.</p>

Output

Run the demo and check the output in the browser.

Output - How to disable the browser back button using JavaScript - Clue Mediator

Output - How to disable the browser back button using JavaScript - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂