Skip to content
Related Articles

Related Articles

Improve Article

How to Disable Browser Back Button using jQuery ?

  • Last Updated : 10 Aug, 2021
Geek Week

While working with some privacy-related projects, we have to make sure that our programming doesn’t have any kind of loopholes. In this article, we will see how we can disable the back button of the browser intentionally so that users cannot get back and access the content. We have many scenarios where we could use this kind of functionality. 

For example, in the payment gateways pages, we can disable the back button so that if the user unintentionally clicks on the back button the payment does not get canceled. For implementing this feature on our page we will toggle through two pages and after that, we will restrict users to get back on the first page.

Example: Create two HTML files in the same folder as we use page1.html and page2.html. In page1.html, add the following code.

index.html




<!DOCTYPE html>
<html>
  
<head>
    <title>Disabling browser back button</title>
    <script src=
        integrity=
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
        crossorigin="anonymous">
    </script>
</head>
  
<body>
    <a href="test2.html">Next page</a>
  
    <script>
        $(document).ready(function() {
            function disableBack() {
                window.history.forward()
            }
            window.onload = disableBack();
            window.onpageshow = function(e) {
                if (e.persisted)
                    disableBack();
            }
        });
    </script>
</body>
  
</html>

 



On the second page, page2.html add the following code. The second page could be anything, first page is important because we are using the script on the first page.

test2.html




<!DOCTYPE html>
<html>
  
<body>
    Click on back button of browser or 
    use the backspace key on keyboard.
</body>
  
</html>

Output:

You can also block the browser’s back button by using Vanilla JavaScript for that you can follow this How to stop the browser back button using JavaScript article.




My Personal Notes arrow_drop_up
Recommended Articles
Page :