Answer: Use the JavaScript window.location
Property
The JavaScript window.location
can be used. You don’t need jQuery to create a page redirect. The syntax window can be used to automatically redirect users from one page to the next. window.location.replace("page_url")
.
The benefit here is, the replace()
method does not save the originating page in the session history, meaning the user won’t be able to use the browser back button to navigate to it, which prevents the user from getting redirected to the destination page once again.
Make a new HTML file. Now, add the following code to it. After 10 seconds, open the file in a browser. You will automatically be redirected to this website’s home page. You will notice that the browser’s back button is still disabled.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Automatic Page Redirect</title>
<script>
function pageRedirect() {
window.location.replace("https://www.tutorialrepublic.com/");
}
setTimeout("pageRedirect()", 10000);
</script>
</head>
<body>
<p><strong>Note:</strong> You will be redirected to the tutorialrepublic.com in 10 sec. You are not able to get back to this page by clicking the browser back button.</p>
</body>
</html>
If you need to redirect the page when an event occurs (e.g. when a user clicks on a button), you can use window.location.href = "page_url"
, This produces the same effect as when someone clicks on a link that navigates to another page.
You can also create another HTML file by adding the following code. Open the file using a web browser. Once it is opened, click on the button. It will take you to the site’s home page. Also, the browser’s back button will be active at this point.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Redirect a Page onClick Event</title>
<script>
function pageRedirect() {
window.location.href = "https://www.tutorialrepublic.com/";
}
</script>
</head>
<body>
<button type="button" onclick="pageRedirect()">Go to Tutorial Republic</button>
<p><strong>Note:</strong> You can go to the tutorialrepublic.com by clicking the button above. You can get back to this page by clicking the browser back button.</p>
</body>
</html>