Javascript Page Redirect

JavaScript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we clicked a URL to reach a page X but internally it directed us to another page Y. It happens due to Page redirection.

How Page Redirect Works.

The implementation of Page redirect are as follows:

Example 1

When we use JavaScript at client side it is quite simple to use of Page Redirect. Need to add a line in head section to redirect the site visitors to a new page.
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript">  
function Redirect() {  
window.location="http://www.tutorialandexample.com";  
}  
</script>  
</head>  
<body>  
<p>Click the following button, you will be redirected to home page.</p>  
<form>  
<input type="button" value="Redirect" onclick="Redirect();" />  
</form>  
</body>  
</html>
Try Now

Example 2

To show a convenient message to visitors before redirecting them to new page. We use setTimeout() is built-in JavaScript function which is used to execute function after a given interval of time.
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript">  
function Redirect() {  
window.location="http://www.tutorialsandexample.com";  
}  
document.write("You will be redirected to main page in 10 sec.");  
setTimeout('Redirect()', 10000);  
</script>  
</head>  
</html>
Try Now

Example 3

In this example shows how to redirect the visitors onto a different page based on their browsers.
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript">  
varbrowsername=navigator.appName;  
if(browsername == "Netscape" )  
{  
window.location="http://www.location.com/ns.htm";  
}  
else if ( browsername =="Microsoft Internet Explorer")  
{  
window.location="http://www.location.com/ie.htm";  
}  
else  
{  
window.location="http://www.location.com/other.htm";  
}  
</script>  
</head>  
</html>
Try Now