Ian Purton

Ian Purton’s Notes

Keeping Track Of The Referrer In Javascript

  • PublishedJuly 11th, 2006
  • Authorian.purton
  • CategoriesJavascript

This Javascript code will add a handler to a cancel button on a form, so that when the button is clicked the user is returned to the page that requested the form.

This is useful when you have more than one route to a form, such as an edit link on a table or an edit link on a details screen.

The script uses a cookie to remember where the user comes from. It also handles the case where the referrer is the form itself, i.e. with struts validation the form may be displayed several times.

First of all saveReferrer() needs to be called on page load.

function saveReferrer()
{
  if(location.href.indexOf('Update') == -1)
    document.cookie = "referrer=" + document.referrer + "; path=/";
}

You’ll need a function to retrieve the referrer.

function getReferrer()
{
	var nameEQ = "referrer=";
	var ca = document.cookie.split(';');
	for(var i=0;i
	{
	  var c = ca[i];
	  while (c.charAt(0)==' ') c = c.substring(1,c.length);
	  if (c.indexOf(nameEQ) == 0) return c.substring(
	  nameEQ.length,c.length);
	}
	return null;
}

Finally, the cancel button needs on onclick handler.

onclick="document.location.href = getReferrer();"

"Keeping Track Of The Referrer In Javascript" was published on July 11th, 2006 and is listed in Javascript.

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

(required)
(required)
 

Subtraction Wordpress Theme by Ian Purton