How to Redirect to Another Webpage using JavaScript?
Last Updated :
25 Oct, 2024
JavaScript can redirects the users from current page to another webpage (different URL) with and without requiring any manual action (like clicking a link). To redirect to another weboage in JavaScript we need to manipulate the window.location object and it will allow us to navigate programmatically.
Using window.location.href
The window location href property is used to set or return the complete URL of the current page. The Location href property can also be used to set the href value point to another website or point to an email address. The Location href property returns a string that contains the entire URL of the page, including the protocol.
Syntax
window.location.href = "URL"
Example: This example redirects to gfg by updating the window.location.href in defined redirect function when the button is clicked.
HTML
<!DOCTYPE html>
<html>
<body>
<p>
Redirect to another page using
<i>window.location.href.</i>
</p>
<button onclick="redirect()">
Redirect to GFG
</button>
<!-- Redirect to Another Webpage -->
<script>
function redirect() {
window.location.href =
"https://www.geeksforgeeks.org/";
}
</script>
</body>
</html>
Output
Using location.replace() Method
The location replace() method is used to replace the current document with the specified one. This method is different from the assign() method as this removes the current document from the document history, therefore it is not possible to go back to the previous document using the ‘back’ button.
Syntax
location.replace("URL");
Example: Redirects the page to GeeksforGeeks official website by updating the location.replace in defined redirect function when the button is clicked.
HTML
<!DOCTYPE html>
<html>
<body>
<p>
Redirect to another page using
<i>location.replace.</i>
</p>
<button onclick="redirect()">
Redirect to GFG
</button>
<!-- Redirect to Another Webpage-->
<script>
function redirect() {
location.replace("https://www.geeksforgeeks.org/");
}
</script>
</body>
</html>
Output
Use Cases to Redirect to Another Webpage
To redirect to a relative URL in JavaScript, you could use window.location.href. It
is a property in JavaScript that represents the complete URL of the current page. It can be used to get the current URL or to navigate to a new URL by assigning a new URL to it.
We will use JavaScript to redirect the web page to another web page if the user is ideal for 10 seconds.
There are two approaches used to redirect the browser window back: