How to disable Browser Back Button Functionality using JavaScript

Topics

Introduction

In this article, I will explain with the help of an example to prevent a user from navigating to the previous page using the back button of the browser. It is not possible to disable or block that functionality on the browser but we can prevent users from clicking back button using the following example.

To prevent users from clicking back button add following code inside your webpage’s head section

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

For example, I am creating to 2 webpages here. Register & home. Once user open register webpage, on click event I am redirecting the user to home page after that I am preventing the user to go back to register page using back button.

Create Register.html file and add following code in Register.html webpage

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Register Webpage</title>
    <script type="text/javascript">
        function preventbackbutton() { window.history.forward(); }
        setTimeout("preventbackbutton()", 0);
        window.onunload = function () { null };
    </script>
</head>
<body>
    <h3>Register Webpage</h3>
    <hr />
    <a href = "Home.html">Redirect to Home</a>
</body>
</html>

Create home.html webpage & add following code in home.html webpage

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Home Webpage</title>
</head>
<body>
    <h3>Home Webpage</h3>
    <hr />
    <a href="register.html">Redirect to register</a>
</body>
</html>

Result

Leave a Comment