How to redirect to a new URL using JavaScript

By

Learn how to redirect to another URL with JavaScript, choose between location.assign() and location.replace(), and add a link fallback.

~~~

I wanted to solve this specific use case, track the number of people that subscribe to my newsletter as a “goal” in my analytics.

I’m moving away from Google Analytics where you can setup “funnels goals”, meaning you visit page X, you visit page Y, that’s a goal.

It’s not possible in the new analytics I’m trying (Plausible) so I had to find a trick.

After you subscribe you land on a specific page where you can download some stuff.

I can’t say “the goal is to visit this page” because people might save it, bookmark, get back later.

After subscribing, I sent people to a temporary page and redirected them two seconds later:

<script>
  setTimeout(() => {
    window.location.replace('/page')
  }, 2000)
</script>

location.replace() does not keep the temporary page in the browser history. Pressing Back therefore returns to the page before it. Use location.assign('/page') if you want the redirect page to remain in history.

Always include a normal link as a fallback:

<p>Redirecting you to the downloads in 2 seconds.</p>
<p><a href="/page">Continue to the downloads</a></p>

For a permanent URL move, configure an HTTP redirect on the server or hosting platform instead. JavaScript redirects are for client-side flows like this one.

~~~

Related posts about js: