Javascript Redirect To Another Page

In this tutorial,we will learn how to use JavaScript to redirect to a new URL or page.

Sometimes, you want to redirect users to a new URL, e.g., after users log in, you want to redirect them to the admin page.

JavaScript has APIs that allow you to redirect to a new URL or page.

 

Redirect Into a Webpage

There are several ways to redirect to another webpage with JavaScript. Most popular location.href and location.replace:

To redirect to a related JavaScript URL you can use

window.location.href = 'https://www.krtricks.in';

window.location.href returns the href (URL) of the current page

Example

<!DOCTYPE html> 

<html> 

<head> 

  <script> 

    function newUrl() { 
     window.location.href="https://www.krtricks.in"; 

    } 

  </script> 

</head> 

<body> 
Go to www.krtricks.in
  <input type="button" value="Go" onclick="newUrl()"> 

</body> 

</html>
Redirect on page loading

If you want to redirect to a new page on loading, then use this code:

window.onload = function() {
    location.href = "https://www krtricks.in";
}
To redirect to a related url you can use

document.location.href = '/about.php';

Both windows.location.href and document.location.href are the same.

Redirect Using Replace Function

The replace() method of the Location interface replaces the current resource with the one at the provided URL.

location.replace("https://www.krtricks.in")

Example

<!DOCTYPE html>
<html>
<body>

<h2>Redirect to other page</h2>
<p>The replace() method replaces the current document with a new.</p>

<button onclick="myUrl()">Replace Page</button>

<script>
function myUrl() {
  location.replace("https://www.krtricks.in")
}
</script>

</body>
</html> 

 

Leave a Comment

Your email address will not be published.