/    /  Javascript-Forwarding

Javascript-Forwarding

 

Redirect means a mechanism of sending search engines and users on a different URL from the original one. The redirected webpage can be on the same server or on a different server. It can also be on the same website or on different websites. Sometimes when we clicked on a URL, we directed to another URL. It happens because of the page redirection. It is different from refreshing a page.

 

<link rel = "canonical" href = "https://www.i2tutorials.com/" />

 

There are different methods used for performing page redirection, but location.href and location.replace() are widely used.

 

window.location and window.location.href:

 

window.location object is a property of the window object. There are several methods to redirect a web page or website. Almost all methods are related to the  object.

 

It can be used for getting the address of the current URL or the website address. The  object can be written without adding the window prefix.

 

location.replace():

 

It is used for replacing the original document with a new one.

 

Syntax:

 

window.location.replace("new URL");

 

Example:

 

<html>
<head>
<script type = "text/javascript">
function page_redirect(){
window.location = "https://www.i2tutorials.com/";
}
</script>
</head>

<body>
<h2> This is an example of the page redirection </h2>
<p> Click the following button to see the effect. </p>

<form>
<input type = "button" value = "Redirect" onclick = "page_redirect()" />
</form>

</body>
</html>

 

OUTPUT:

 

Javascript-Forwarding

 

Javascript-Forwarding

 

Example:

 

we are using the setTimeout() method

 

<html>
<head>
<script type = "text/javascript">
function page_redirect() {
window.location = "https://www.i2tutorials.com/";
}
setTimeout('page_redirect()', 5000);
</script>
</head>

<body>
<h2> After 5 seconds, you will redirected to another page. </h2>
<p> Wait for 5 seconds to see the effect. </p>
</body>
</html>

 

OUTPUT:

 

Javascript-Forwarding

 

Javascript-Forwarding

 

Example:

 

using the replace() method for page redirection.

 

<!DOCTYPE html>
<html>
<head>
<script>
function page_redirect() {
  location.replace("https://www.i2tutorials.com/")
}
</script>
</head>
<body>

<h2> Example of redirecting a page using replace() </h2>
<p> Using the replace() the currct document will replace with new one. </p>
<p> Click the following button to see the effect. </p>
<button onclick = "page_redirect()"> Replace </button>
</body>
</html>

 

OUTPUT:

 

Javascript-Forwarding

 

Javascript-Forwarding