Code Premix

Restrict or Disable browser back button using JavaScript

📅April 22, 2022

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.

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.

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.