Skip to content
Related Articles

Related Articles

Improve Article
How to stop browser back button using JavaScript ?
  • Last Updated : 23 Oct, 2019

In this article, we will discuss how to write a javascript function which will prevent the user to navigate back to the last or previous page. There are so many ways to stop the browser back button most popular and will work in all conditions. You can add code to the first or previous page to force the browser to go forwards again and again so when the user tries to back to the previous page the browser will take him again in the same.

This can be done by making custom functions like this:
Example 1:

  • Code 1: Save this file as Login.html for the first page.




    <!DOCTYPE html>
    <html>
          
    <head>
        <title>
            Blocking Back Button
            using javascript
        </title>
          
        <style type="text/css">
            body {
                font-family:Arial;
                color:green;
            }
        </style>
          
        <script type="text/javascript">
            window.history.forward();
            function noBack() {
                window.history.forward();
            }
        </script>
    </head>
      
    <body>
        <h1>GeeksforGeeks</h2>
          
        <p>
            Click here to Goto 
            <a href="b.html">
                Link to second page
            </a>
        </p>
    </body>
      
    </html>
  • Code 2: Save this file as b.html for the second page.




    <!DOCTYPE html>
    <html>
          
    <head>
        <title>
            Blocking Back Button
            using javascript
        </title>
    </head>
      
    <body>
         <h3>This is second page</h3>
           
         <p>
             On this page, back button
             functionality is disabled.
         </p>
    </body>
      
    </html>
  • Output:

Example 2:

  • Code 1: Save this file as a.html for the first page.




    <!DOCTYPE html>
    <html>
          
    <head>
        <title>First Page</title>
          
        <script type="text/javascript">
            function preventBack() {
                window.history.forward(); 
            }
              
            setTimeout("preventBack()", 0);
              
            window.onunload = function () { null };
        </script>
    </head>
      
    <body>
        <h3>This is first page</h3>
        <hr />
        <a href = "b.html">Goto second Page</a>
    </body>
      
    </html>
  • Code 2: Save this file as b.html for the second page.




    <!DOCTYPE html>
    <html>
          
    <head>
        <title>Second Page</title>
    </head>
      
    <body>
        <h3>
            Second Page - Back Button
            is disbaled here.
        </h3>
        <hr />
    </body>
      
    </html>
  • Output:



My Personal Notes arrow_drop_up
Recommended Articles
Page :