Auto Ad Code

Wednesday, August 18, 2010

Disable browser back button

Sometimes we need a functionality that user should not be allowed to go to previous page using the browser back button. Most of us then try to search that how we can disable the browser back button.
A simple and straight answer is that browser's back button can not be disabled because browser resides at user's machine and not on Server. All we can do is to prevent a page for being cached. So if a page is not being cached at client then browser back button will not allow a user to navigate to that page.
What's the procedure?
Procedure is pretty much easy and described in below.
A very important thing to remember is that you have to use this code in page1 in case you want that page1 should not be available using back button of browser. i.e. use this code in that page which you want not available at browser back button.

==================================
Use following 3 lines in HEAD section (HTML view)

<meta http-equiv="cache-control" content="no-store"/>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="pragma" content="no-cache"/>


use following lines in Page_Load (Code behind)
VB
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Buffer = True
Response.ExpiresAbsolute = DateTime.Now().AddDays(-1)
Response.Expires = 0
Response.CacheControl = "no-cache"



C # (C Sharp)
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now().AddDays(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
==================================

This should solve your issue.

6 comments:

  1. hi,

    when i inserted the code

    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.Buffer = True
    Response.ExpiresAbsolute = Now() - 1
    Response.Expires = 0
    Response.CacheControl = "no-cache"

    Now() - 1 was underlined. yet still i tried running it in the browser and it gives me an error message

    do i declare a variable? or what do I do

    ReplyDelete
  2. @gom
    Sorry for the delayed reply and the inconvenience. I have updated the post and hopefully now it will be working fine.

    ReplyDelete
  3. go an error for " Response.Buffer = True
    Response.ExpiresAbsolute = Now() - 1" this code
    and error is "Non-invocable member 'System.DateTime.Now' cannot be used like a method"

    ReplyDelete
  4. u r coding wrong....
    try
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Buffer = true;
    Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
    Response.Expires = 0;
    Response.CacheControl = "no-cache";

    ReplyDelete
  5. @anii
    use the code provided bu Kuldeep. Code in post was for VB.Net (Though now I have added code for C# as well).

    Thanks @Kuldeep

    ReplyDelete
  6. is this issue has any effect on cookies cashing !!??

    ReplyDelete