How Do I Disable The Browser Back Button In React JS?

Richelle John
2 min readAug 17, 2023

--

In this short article, we’ll tell you the best way to cripple the program back button utilizing JavaScript.

Now and again we want to keep the client from returning to the past page for security. So we can without much of a stretch confine the back button utilizing JavaScript.

There are numerous ways of handicapping the back button in the program. Here, we’ll make sense of a straightforward way for stop the back button utilizing JavaScript.

Read Also: Disable The Browser Back Button In React JS

You can include the code the first or past page so that when a client attempts to divert on the past page, the program will divert to a similar page.

To do this, you want to add the accompanying code to the head part 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 make two pages Login and Home. After login, the client will be diverted to the Landing page, and utilizing the program back button will keep it from getting back to the login page from the landing page.

<!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 connect to divert on the Landing page. Presently, we will make a home.html record and compose the accompanying code.

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

--

--

Richelle John
Richelle John

Written by Richelle John

With over five years' experience in leading marketing initiatives across Europe and the US, I am a digital marketing expert. Visit Here https://bit.ly/3Wsauvr

Responses (2)