How to disable the browser back button using JavaScript

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.

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

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

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..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

  1. Sam Ramsan says:

    Thank You for sharing such a useful snippet.
    It works beautifully.

Leave a Reply

Your email address will not be published. Required fields are marked *