Redirecting to a New URL Using JavaScript

Here's how you can redirect to a new URL using JavaScript:

Using window.location.href

The most straightforward method to redirect to a new URL is by setting the window.location.href property to the target URL. This method simulates a click on a link by the user and is suitable for most redirect needs.

window.location.href = 'https://example.com';

Using window.location.replace()

If you want to redirect the user without keeping the current page in the session history, you can use the window.location.replace() method. This is useful if you do not want the user to be able to use the back button to navigate back to the original page.

window.location.replace('https://example.com');
  • Use window.location.href if you want the user to be able to navigate back to the original page using the back button.
  • Use window.location.replace() to redirect the user and prevent them from returning to the original page via the back button.
JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.