Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Monday 12 March 2012

Disabling the back button Of Browser using ASP.NET

How to disable browser's Back button in ASP.NET


Almost every ASP.NET developer face this problem at least once in his entire career. There could be numerous reasons for disabling the browser's back button. The site is secure and the user should not be allowed to go back to the previous page, for online exams site the student should be not allowed to view the question once answered etc could be the reasons for disabling the back button.
What does the browser back button actually do?
The browser maintains a cache of the pages that are visited by the user. Once the user clicks on the back button, the browser flushes the cached version of the page. Now to avoid this situation we can think of two solutions
1. Whenever the user clicks on the "back" button, again redirect the user to the "next" page using the JavaScript: history.forward(1). This JavaScript needs to be written on the onload JavaScript event of the web page. Thus the user will never be able to come to the previous page. But this is not a reliable technique since some of the browser's do not invoke the onload function on pressing the "Back" button.
2. Another solution is to avoid the browser maintaining the cache of the pages that a user visits. Yes, this can be achieved through AsP.NET server side coding. Add the following code to the Page_Load event of ASP.NET web page or MasterPage:
// Disable the Cache
Response.Buffer= true;
Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
Response.Expires =-1500;
Response.CacheControl = “no-cache”;

// Check for your SessionID
if(Session["SessionId"] == null)
{
   Response.Redirect (”Home.aspx”);
}
This code will disable the cache for the current page. The pages contents are maintained in memory i.e. in buffer. Once the user logout the session and buffer will be cleared. As we are not maintaining the cache for the page, the back button will not work anyways. It means we have successfully disabled the Back button.

No comments:

Post a Comment