Redirect a user without creating browsing history

Redirect a user without creating browsing history

When writing web applications, it is sometimes desirable and/or necessary to redirect the user without creating history in the browser. This prevents the user from hitting the back button and ending up at a page.

For example, when a form I have created submits to a JSP that processes the form and outputs status messages, the user is forwarded onwards after the processing is complete. If the user press back, the user would end up at the JSP that outputted the status messages, which is not the behavior the user would likely expect. If they hit back, they want to go back and edit something and hit save again.

Another example is changing details of a user account. When the page is saved, a common task would be to submit the form to a servlet or JSP, then redirect back to the page. We don’t want the user to hit back and reach an out of date page.

This can be done via JavaScript using location.replace and in Mozilla/Firefox with location.href. These change the URL in address bar and load the page specified, but without creating history. Changing location alone creates history.

In the example below, ${navigateTo} stores the location to forward the user to.

if (document.images) // check for IE
  location.replace('&{navigateTo}');
 else // Mozilla, Firefox
  location.href='&{navigateTo}';

And to give time for the user to see the output before forwarding them:

if (document.images)
  window.setTimeout("location.replace('&{navigateTo}')","5000");
 else
  window.setTimeout("location.href='&{navigateTo}"',"5000");

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *