How to Redirect a Web Page with JavaScript

To redirect a URL page with Javascript you need to set the window.location object. There are several ways to change the location property on the window object:

  • window.location.href - returns the URL of the current page
window.location.href='http://www.w3docs.com/'
  • window.location.hostname - returns the name of the internet host (of the current page)
window.location.hostname='http://www.w3docs.com/'
  • window.location.replace - removes current URL from the history and replaces it with a new URL which makes it impossible to go to the previous page using the back button.
window.location.replace='http://www.w3docs.com/'
  • window.location.assign - keeps the history and it is possible to go back to the original page clicking on the back button.
window.location.assign='http://www.w3docs.com/'
Recommendation: You had better use window.location.href, because the replace method navigates to the URL without adding a new record to the history; thus the reader won’t be lost in an endless back-button mess.
Recommendation: Use .href if you want to make the user click on a link, and use .replace if you're going to make an HTTP redirect.
Note: This won’t work if JavaScript is disabled in the browser.

Learn how to redirect web pages with HTML, PHP , Apache and Node.js .


Do you find this helpful?

Related articles