How to redirect to a webpage in a browser using JavaScript?

Published December 14, 2020

To redirect to a webpage in browsers using JavaScript, we can use the location property on the global window object.

Let's say our redirect url is https://google.com, all we have to do is set the window.location value to the redirect URL.

// redirect to a webpage
window.location = "https://google.com";

Along with the above solution, JavaScript is lovely enough to provide us with there are 3 more other ways to achieve the same thing,

  • Changing the value of window.location.href to the redirect URL. This way is similar to a user clicking on a link.
// redirect to webpage
// similar to user clicking on a link
window.location.href = "https://google.com";
  • Passing the redirect URL as an argument to the assign() method on the window.location object.
window.location.assign("https://google.com");
  • Passing the redirect URL as an argument to the replace() method on the window.location object.
window.location.replace("https://google.com");

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter