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.
Title of the document
let url = "//www.w3docs.com";
window.location.href = url;
- window.location.hostname - returns the name of the Internet host of the current page.
Title of the document
Click and go to the page
function redirectFunc[] {
window.location.href = "//www.w3docs.com/";
}
- window.location.replace - removes current URL from the history and replaces it with a new URL which disables to go to the previous page using the back button.
Title of the document
function redirectFunc[] {
window.location.replace["//www.w3docs.com/"];
}
setTimeout["redirectFunc[]", 2000];
- window.location.assign - keeps the history and makes it possible to go back to the original page just clicking on the back button.
Title of the document
function redirectFunc[] {
window.location.assign["//www.w3docs.com/"];
}
setTimeout["redirectFunc[]", 2000];
You had better use window.location.replace instead of .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.
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.
If JavaScript is disabled in the browser, this will not work.
Learn how to redirect web pages with HTML, PHP , Apache and Node.js .
Back to previous page As you can see this requires JavaScript to be enabled in the client browser. Otherwise this code will not work.
This article is written by plus2net.com team.