How to redirect to another web page using JavaScript

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: May 19, 2022.

Using JavaScript, you can run some code immediately upon page load that will send a user to another page (i.e. redirect the user).

Table of contents

Redirecting

For immediate directing, it is best to use the following code:

window.location.replace('https://example.com');

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.

Then, select these elements in JavaScript.

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.

<!--- HTML start --->
<div>Redirecting you to <span id="redirect-url"></span> in <span id="redirect-countdown"></span></div>
<!--- HTML end--->

<!--- JavaScript start --->
<script>
// Select span elements to write to:
const redirectCountdown = document.getElementById('redirect-countdown');
const redirectURL = document.getElementById('redirect-url');

// Set url and write to DOM as redirect-url
const url = 'https://example.com';
redirectURL.innerText = url;

// Create countdown starting value and write to redirect-countdown
let countdown = 3;
redirectCountdown.innerText = countdown;

// Each second, subtract 1 from countdown and update redirect-countdown value
setInterval(function() {
  countdown--
  redirectCountdown.innerText = countdown;
},1000)

// After countdown time is up, make the redirect
setTimeout(function() {
  window.location.replace('http://example.com');
},countdown*1000)
</script>
<!--- JavaScript end --->

Summary

By accessing 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.

Related links