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.
1 2 3 4 5 | <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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!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 - Clue Mediator</h3> <p>Click here to redirect to the <a href="home.html">Home Page</a></p> </body> </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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h3>Home Page - Clue Mediator</h3> <p>On this page, back button functionality is disabled.</p> </body> </html> |
Output
Run the demo and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂
Thank You for sharing such a useful snippet.
It works beautifully.
Hi Sam, I’m glad it helped!