Monday 8 June 2020

Browser back button issue after logout

The browser Back button is an option to go back to previously visited pages. The back button can be considered as a pointer that is linked to the page previously visited by the user. Browser keeps a stack of the web pages visited as a doubly-linked list.

The back button works by stepping through the history of HTTP requests which is maintained by the browser itself. This history is stored in browsers cache that consists of the entire page content with resources like image and scripts. This enables browser to navigate backwards and forwards through the browser history and have each page displayed instantly from cache without the delay of having it retransmitted over the internet from the server.

Just to handle the scenario of getting page content from server, browsers have a Refresh button that transmits the request to web server and get back the fresh copy of entire page. Internally, this also replaces the copy of the page in the browser's cache.

So, what's the basic reason behind it? It's, browser's Cache!
Now, what can be done to handle the scenario? Surely on logout event one does clear the session. Post which, browsers cache needs to be handled such that browser has no history (this will make back/forward button in browser grayed out disabled.) Here are various ways of how one can do it:

Option #1: Set Response Cache settings in code-behind file for a page
// Code disables caching by browser.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
Option #2: Set META tag for HTTP cache settings in your ASPX page header
<META Http-Equiv="Cache-Control" Content="no-cache"/>
<META Http-Equiv="Pragma" Content="no-cache"/>
<META Http-Equiv="Expires" Content="0"/>
Option #3: Clear browser's history through JavaScript using script tag
//clears browser history and redirects url
<SCRIPT LANGUAGE="javascript">
function ClearHistory()
{
     var backlen = history.length;
     history.go(-backlen);
     window.location.href = loggedOutPageUrl
}
</SCRIPT>
Option #4: Clear browser's history through JavaScript injecting through code-behind file via Response
protected void LogOut()
{
     Session.Abandon();
     string loggedOutPageUrl = "Logout.aspx";
     Response.Write("<script language="'javascript'">");
     Response.Write("function ClearHistory()");
     Response.Write("{");
     Response.Write(" var backlen=history.length;");
     Response.Write(" history.go(-backlen);");
     Response.Write(" window.location.href='" + loggedOutPageUrl + "'; ");
     Response.Write("}");
     Response.Write("</script>");
}
Option #5: Clear browser's history through JavaScript injecting through code-behind file via Page.ClientScript
Page.ClientScript.RegisterStartupScript(this.GetType(),"clearHistory","ClearHistory();",true);

No comments:

Post a Comment