Background
Sometimes their is a need to disable the back button of the browser for security reasons so as to prevent the user from navigating between the pages by using the browser arrow buttons.
Problem
Suppose their is a Login page, when i login into the application, the page will be redirected to the page where I perform all my tasks, after doing all my work, I will logout from the application and the page again will get redirected to the Login page, at that time when i will click on the browser next arrow button it will allow me to show the next page that i have earlier used to Login without the need of new login; so to avoid this problem we need to disable the browser button.
Now let us see how to do it...
open VS --create New Web site-add two web page...
After adding the two web pages, write the following javascript code.
- <script type ="text/javascript">
-
- window.onload = window.history.forward(0); //calling function on window onload
-
- </script>
Create the same page as above to navigate from the first page to the second page.. now the two pages with the entire code will look like the following:
First.aspx Page
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <script type ="text/javascript">
-
- windowwindow.onload = window.history.forward(0);
-
- </script>
-
- <title></title>
- </head>
- <body bgcolor="silver">
-
-
-
- <form id="form1" runat="server">
- <h4>This is First Page</h4>
- <br /><br /><br />
- <div>
- <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Goto Second Page" />
- </div>
-
- </form>
- </body>
- </html>
SecondPage.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <script type ="text/javascript">
-
- windowwindow.onload = window.history.forward(0);
-
- </script>
- <title></title>
- </head>
- <body bgcolor="silver">
- <form id="form1" runat="server">
- <div>
- <h4>This is second Page</h4>
- </div>
- </form>
- </body>
- </html>
Now run the application, the first page will look like the following:
Now click on the Goto Second Page button, it will be redirected to the next page as the following:
Now try to click on the above browser navigation button, now click on the above arrow button. here you will see that it will not directly allow you to navigate on the first page and from the first page to the second page.
Summary
It's a very small trick but it will play an important role in the security of the application, I hope this blog is useful, if you have any suggestion then please suggest me.