How to Redirect a Web Page with JavaScript
To redirect a URL page with Javascript you need to set the window.location object. Learn how to do it.
To redirect a web page with JavaScript, you need to set the <kbd class="highlighted">window.location</kbd> object. There are several ways to change the location property on the window object:
<kbd class="highlighted">window.location.href</kbd>- returns the URL of the current page.
How to Redirect a Web Page with Javascript
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script>
let url = "https://www.w3docs.com";
window.location.href = url;
</script>
</body>
</html><kbd class="highlighted">window.location.hostname</kbd>- sets the hostname of the current page.
How to Redirect a Web Page with Javascript
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<button type="button" onclick="redirectFunc()">Click and go to the page</button>
<script>
function redirectFunc() {
window.location.hostname = "www.w3docs.com";
}
</script>
</body>
</html><kbd class="highlighted">window.location.replace</kbd>- removes the current URL from the history and replaces it with a new URL, preventing navigation to the previous page using the back button.
How to Redirect a Web Page with Javascript
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script>
function redirectFunc() {
window.location.replace("https://www.w3docs.com/");
}
setTimeout(redirectFunc, 2000);
</script>
</body>
</html><kbd class="highlighted">window.location.assign</kbd>- keeps the history and allows the user to return to the original page using the back button.
How to Redirect a Web Page with Javascript
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script>
function redirectFunc() {
window.location.assign("https://www.w3docs.com/");
}
setTimeout(redirectFunc, 2000);
</script>
</body>
</html>Use window.location.href or .assign for standard redirects to preserve back-button navigation. Use .replace only when you want to prevent the user from returning to the previous page (e.g., after a login).
Use .href or .assign for standard client-side navigation. Use .replace when you need to remove the current page from the session history.
If JavaScript is disabled in the browser, this will not work.
Learn how to redirect web pages with HTML, PHP, Apache, and Node.js.