Back to the Konsensys

Back to Tips
Disabling the Browser Back Button
by
George Van Treeck

It is often important to disable the browser back button in "web applications" that use HTTP POST (very common with database applications) and AJAX, which replace the contents of a web page with new content. The problem is that if a user hits the browser back button the user completely exits the web application rather going back to last viewed content within the application. And users find that very confusing and frustrating.

You can psudo-disable the browser back button as follows:

  1. Server-side code tests for a new user session.
  2. If the session is new, then output a "fake" web page, that contains javascript, which immediately requests the same page again.
  3. This time, the server-side code detects that the user session is not new and responds with a "real" web page.

When the user hits the browser back button, it goes back to the fake page, which immediately opens a real page. In a Java servlet the code would like the following:

final static protected String fake_page = ...
public void doPost(
      HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {
  if (request.getSession().isNew())
    response.getWriter().println(fake_page);
  else
    response.getWriter().println(getPage(request));
}

Where "getPage()" is your application specific code that returns your response. But his has major flaw. When the user hits the browser back button, the web application will display the first (home) page content rather than the previous content, which will confuse the user. So, we need make the handling of browser back button a little more robust:

final static protected String fake_page = ...
public void doPost(
      HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {
  HttpSession session = request.getSession();
  if (session.isNew())
    response.getWriter().println(fake_page);
  else {
    // PageStack is a class you write to track navigation
	PageStack stack =
      (PageStack) session.getAttribute("PageStack");
    // Use whatever query parameter you wish.
	// Here we use "page_name".
    if (request.getParameter("page_name") == null) {
	  // Entering the start page
	  if (stack != null) // Browser back button probably used.
      	 stack.pop(); // Go back to previous page
	  else {
	     stack = new PageStack();
		 session.setAttribute("PageStack", stack);
      }
    }
    String page = getPage(request, stack);
	stack.push(page);
    response.getWriter().println(page);
  }
}

In the case above, we add the PageStack parameter to getPage(), which tracks the current positon. PageStack is class that you write by extending java.util.Stack. You can use JSP/ASP to do the same thing. I prefer writng servlets (or PHP).


Copyright (C) 2010 George Van Treeck. All rights reserved.