Click here to Skip to main content
15,881,819 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

Browser Back Button Issue After Logout

Rate me:
Please Sign up or sign in to vote.
4.92/5 (12 votes)
21 Feb 2013CPOL4 min read 189.9K   3.9K   11   17
This is an alternative for "Browser back button issue after logout".

Introduction

Generally when any user logs into any web application, we store some value in session. The session continues the user existence until logout. After logout, we clear/abandon the session and redirect to login page. In that state, the user is out of website and the secret information is now secure or nobody is authorized to view/access the information.

But the problem is now, from this redirect login page if user clicks the back button of browser, it again goes to the previous visited page although the page is already logged out. The main reason is the browser’s cache. This is because while user logs out the session, the session is abandoned in the server side. But after clicking the back button of the browser, the previous page is not postback, the client side just opens from cache. It only works if the back page refreshes/reloads, because in that period the page becomes postback.

The common problem has many solutions but each and every solution has some limitations. Let’s see the existing solutions that we can find easily in searching.

Existing Solution 1: Clear Cache/No-Cache

C#
// Code disables caching by browser. Hence the back browser button
// grayed out and could not causes the Page_Load event to fire 
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore(); 
Limitations
  • Server Side code and for that it does not work without postback.
  • I have to clear my cache by force (I don’t want to clear my cache).

Existing Solution 2: Use Meta Tag for No-Cache

XML
<meta Http-Equiv="Cache-Control" Content="no-cache">
<meta Http-Equiv="Pragma" Content="no-cache">
<meta Http-Equiv="Expires" Content="0"> 
Limitations
  • This is not possible because Back history is maintained by browser, you will need to close the window.
  • I have to clear my cache by force (I don’t want to clear my cache).

Existing Solution 3: Clears Browser History and Redirects URL

JavaScript
//clears browser history and redirects url
<SCRIPT LANGUAGE="javascript"> 
{  
     var Backlen=history.length;   
     history.go(-Backlen);   
     window.location.href=page url 
}
</SCRIPT> 
Limitations
  • Same limitation like solution 1: Does not work in all browsers, moreover I have to clear my history although I don't want to do this.

Existing Solution 4: Call JavaScript from Server Side to Clear Cache

Page.ClientScript.RegisterStartupScript(this.GetType(),"cle","windows.history.clear",true); 
Limitation
  • Server side code, so it does not work without postback again. Moreover I have to clear my history although I don't want to do this.

Alternative Solution

From the above explanation, we can understand that when the user clicks on back button of browser, the client side loads only. Even no postback happens in that period. For that, I handle the problem on the client side. You can think that if we check the session value in client side with JavaScript, then the problem will solve? My answer is: NO. Because when we clear/abandon the session value, its value changed only server side but the value which has already taken with JavaScript variable, it stores on cache as well.

The only one solution is if we can check the server session value from client side on loading moment, then we can overcome this issue.

Analysis of Code

Login Page: Login process is very common like I store a session value while login is successful.

C#
protected void btnSave_Click(object sender, EventArgs e)
{
   // User Name and Password Check here
   //After successful login store a session value 
   Session["user"] = "user:Desme-BD";
   Response.Redirect("/frmContentHome.aspx", true);
} 

I have stored "user:Desme-BD" in session "user".

Master Page(Server Side): In content page, I have checked the session value or Redirect the page to Login page.

C#
// this is simple method only checking the session value while user login
private void CheckLogin()
{
            string domain = Request.Url.Authority.ToString();
            BaseURL = "http://" + domain + "/";
            //Load menu or Do Any database related work
            if (Session["user"] != null)
            {
                lnkLogin.Text = "Logout";
                lnkLogin.PostBackUrl = BaseURL + "frmLogout.aspx";
            }
            else
            {
                Response.Redirect(BaseURL + "frmLogin.aspx", false);
            }
} 

Logout Page: I also clean the session value while logout with those common methods.

JavaScript
Session.Abandon();
Session.Clear();
Session.RemoveAll();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("frmLogin.aspx", false);<span style="font-size: 9pt;"> </span>

The Method which Checks Server's Session with Client Side

Master Page(Client Side)

On ASPX page, I use the Jquery with JSON and check the Session value with LogoutCheck() WebMethod.

JavaScript
<script type="text/javascript">
        $(document).ready(function () {
            CheckingSeassion();
        });
        function CheckingSeassion() {
            $.ajax({
                type: "POST",
                url: "frmLogout.aspx/LogoutCheck",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d == 0) {
                        window.location = '<%= BaseURL %>' + "frmLogin.aspx";
                    }
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
</script> 

The LogoutCheck() WebMethod checks the session value from application server on client side loading moment.

I created this method on frmLogout.aspx page like this:

C#
[WebMethod]
public static int LogoutCheck()
{
   if (HttpContext.Current.Session["user"] == null)
   {
       return 0;
   }
   return 1;
}

Now, when user logs out the page, it redirects to logout page and clears and abandons the session values. Now when user clicks back button of browser, the client side only loads and in that period the CheckingSession() WebMethod fires in JQuery and it checks the session value LogoutCheck() WebMethod. As the session is null, the method returns zero and the page redirects again in login page. So, I don't have to clear the cache or clear any history of user's browser.

Download the solution-> browse frmLogin.aspx -> give any password and Login-> now Logout-> click back button on your browser and notice.

Advantages

  • Works on client side page load. No need to postback because it's calling with Ajax.
  • No need to remove cache/history
  • No need to disable back button of web browser

Limitations

This tip also has a limitation that when user clicks the back button of the browser, the back page shows for 1 or half second because of executing the WebMethod.

History

  • 20-February-2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
AnswerASP.NET MVC Pin
Nkhumiseni kholophe21-Jul-23 2:18
Nkhumiseni kholophe21-Jul-23 2:18 
AnswerBrowser Back Button Issue After Logout Pin
vijayaraj139-Jun-15 22:00
vijayaraj139-Jun-15 22:00 
QuestionAnother solution in Asp.net Pin
syed210911-Feb-15 4:53
syed210911-Feb-15 4:53 
Questionfox6 Pin
Member 108635324-Jun-14 0:01
Member 108635324-Jun-14 0:01 
Question[My vote of 1] Plagiarism Pin
Kosimek25-Apr-14 8:27
Kosimek25-Apr-14 8:27 
Questionsimple solution Pin
SurangiTi9-Mar-14 19:43
SurangiTi9-Mar-14 19:43 
BugOne issue Pin
Member 99638755-Jun-13 20:00
Member 99638755-Jun-13 20:00 
QuestionIssue Pin
Member 100717243-Jun-13 23:55
Member 100717243-Jun-13 23:55 
QuestionIssue Pin
Member 100717243-Jun-13 23:31
Member 100717243-Jun-13 23:31 
QuestionThe Ajax function is not being called Pin
aehtiopicus21-Mar-13 10:05
aehtiopicus21-Mar-13 10:05 
GeneralMy vote of 5 Pin
Monjurul Habib1-Mar-13 5:48
professionalMonjurul Habib1-Mar-13 5:48 
GeneralRe: My vote of 5 Pin
Member 98681823-Mar-13 18:04
Member 98681823-Mar-13 18:04 
QuestionNice Post.. Pin
Tanvir E.25-Feb-13 18:27
Tanvir E.25-Feb-13 18:27 
GeneralMy vote of 5 Pin
elpanter22-Feb-13 1:21
elpanter22-Feb-13 1:21 
GeneralRe: My vote of 5 Pin
Member 1051082222-Feb-13 2:02
professionalMember 1051082222-Feb-13 2:02 
GeneralMy vote of 5 Pin
Maksud Saifullah Pulak21-Feb-13 23:01
Maksud Saifullah Pulak21-Feb-13 23:01 
GeneralMy vote of 5 Pin
Sk. Tajbir21-Feb-13 3:44
Sk. Tajbir21-Feb-13 3:44 
nice.. keep it up Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.