Last updated: May 19, 2022.
Table of contents
For immediate directing, it is best to use the following code:
This fully replaces the URL from which the code is run in the browser history.
The advantage of this is that if a user goes back in their browser after the redirect, they will reach the page they were browsing before the redirect.
If you use
window.location.href('https://example.com'), it will also redirect the user. But if a user wants to then go back in the browser, they will access the redirecting page, and this will immediately redirect the user again.
Creating a redirection countdown
You’ve probably seen countdowns before being redirected on web pages before.
To create your own, create your redirect text, adding empty elements for both the redirect URL and countdown value within this text.
In your script, you are going to want to create a recurring update to the countdown value using
setInterval() and a delayed redirect using
setTimeout(). The delay should be the countdown value multiplied by 1000 milliseconds.
location.replace() on the global
window object and passing in a URL, you can redirect a user to another page without the redirect page being saved in the user’s browser history.
- MDN Web Docs: window.location