5-Dec-04 (Created: 5-Dec-04) | More in 'CS-JavaScript'

js: How to write a redirect web page?

<html><head><script>
/*
**************************************************
* The following function will parse the url
* into its constituent parts
**************************************************
*/
function JAbsoluteURL(inUrl)
{
	this.protocol="";
	this.host="";
	this.port="";
	this.hostWithPort="";
	this.webappPrefix="";
	this.resource="";
	this.arguments="";

   //
   //Get the protocol	
   //
   colonIndex = inUrl.indexOf(":");
   this.protocol = inUrl.substring(0,colonIndex);
   
   //
   //Get the host and port
   //
   colonIndex += 3;
   hostSepIndex = inUrl.indexOf("/",colonIndex);
   this.hostWithPort = inUrl.substring(colonIndex, hostSepIndex);
   
   //
   //Get the resource
   //
   this.resource=inUrl.substring(hostSepIndex);
   
   //
   //Get the webapp
   //
   webappEndIndex = inUrl.indexOf("/",hostSepIndex + 1);
   if (webappEndIndex == -1)
   {
   	// no more components
   	this.webappPrefix = this.resource;
   }
   else
   {
   	// more components
   	this.webappPrefix=inUrl.substring(hostSepIndex+1,webappEndIndex);
   }
   
   portSepIndex = this.hostWithPort.indexOf(":");

   if (portSepIndex == -1)
   {
   	//no port
   	this.port="";
   	this.host=this.hostWithPort;
   }
   else
   {
   	this.host=this.hostWithPort.substring(0,portSepIndex);
   	this.port=this.hostWithPort.substring(portSepIndex+1);
   }
   
   //Figure out what the arguments are
   argSepIndex = this.resource.indexOf("?");
   if (argSepIndex == -1)
   {
   	//No arguments available
   }
   else
   {
   	this.arguments=this.resource.substring(argSepIndex + 1);
   }
 
}

/*
**************************************************
* This function will return a relative URL
* from either a relative or absolute URL
**************************************************
*/
function getRelativeURL(inUrl)
{
	firstFour = inUrl.substring(0,4);
	if (firstFour == "http")
	{
		absUrl = new JAbsoluteURL(inUrl);
		return absUrl.resource;
	}
	else
	{
		return inUrl;
	}
}


/*
**************************************************
* This function will redirect the user
* to a diffrent url address
* preserving the webapp and its arguments
**************************************************
*/
function gotoRealIndexPage()
{
	thisUrl = document.location + "";
	absUrl = new JAbsoluteURL(thisUrl);
	
	//Check the following line
	//to see whether you need to 
	//unescape or not
	
	newUrl = "http://your-host-name/akc/display?" 
	        + unescape(absUrl.arguments);
	        
	if (absUrl.arguments != "")
	{
		redirectUrl = newUrl;
	}
	else
	{
		redirectUrl="some-default-address";
	}
	document.location.replace(redirectUrl);
}
</script></head>
<body onLoad="gotoRealIndexPage()">
</body></html>