Explain Codes LogoExplain Codes Logo

How do I redirect to another webpage?

javascript
redirects
user-navigation
single-page-applications
Anton ShumikhinbyAnton Shumikhin·Aug 7, 2024
TLDR

To perform a webpage redirect in JavaScript, you can utilize the built-in object window.location.href:

window.location.href = "http://example.com";

This strategy quickly enables a smooth navigation to a specified webpage.

Types of Redirects

Redirects in JavaScript come in two main flavors, providing different ways to manipulate user navigation.

Non-history-preserving Redirect

If you want to redirect without keeping track of the user's navigation history, use window.location.replace:

window.location.replace("http://example.com"); // Makes a clean getaway

History-preserving Redirect

To keep a record of the user's journey and let them go back to the original page, use window.location.href:

window.location.href = "http://example.com"; // Leaves bread crumbs

Additional Redirect Techniques

There are multiple ways to navigate and manage user history in JavaScript:

Within-site Navigation

To move inside the same domain, use relative paths:

document.location.href = '/path'; // Keeping it in the family

jQuery-based Redirection

If you're a jQuery aficionado, here's the equivalent, though pure JavaScript is more efficient:

$(location).attr('href', 'http://example.com'); // but why though?

Back in Time

Want to revert to the previous page you were on?

window.history.back(); // Marty McFly approves

Topmost Frame

With top.location, you can change the location of the topmost frame:

top.location.href = "http://example.com"; // I'm on top of the world!

The Obsolete window.navigate

Once supported in legacy versions of IE, window.navigate is now outdated:

// Jurassic Code window.navigate("http://example.com");

Preserving HTTP_REFERER

To keep HTTP_REFERER in IE8 or before, create and click an anchor element:

// Old school hack for old school IE var a = document.createElement('a'); a.href = "http://example.com"; document.body.appendChild(a); a.click();

For modern browsers and IE9+, window.location.href maintains HTTP_REFERER.

Redirect Scenarios

Here's how to approach redirection based on different situations:

User-triggered Redirection

A straightforward method for redirecting after a user action like a form submission:

// Listen. React. Redirect. document.getElementById("myButton").addEventListener("click", function() { window.location.href = "http://example.com"; });

Auto-redirect

When you need to redirect after certain events or after a brief delay:

// Patience is a virtue... setTimeout(function() { window.location.href = "http://example.com"; }, 3000); // waits for 3s then redirects

SPA Routing

For Single-Page Applications, client-side routing without full page refreshes can be a boon:

// Smooth operator in SPA window.history.pushState({}, '', '/new-page');

Troubleshooting Redirects

While redirection seems simple, it can present a few puzzles. Here's how to solve them:

Data Privacy

Avoid adding sensitive data in query strings - no one likes URL leakage.

Infinite Loops

Double-check conditions or you might end up redirecting forever. Your users will not appreciate the endless journey.

Post-Redirect-Get Pattern

After a form submission, redirect to a "success" page to avoid duplicate form submissions:

// Because no one likes double-dipping window.location.href = 'formSuccessPage.html';

Deferred Redirects

Tricky business when redirecting after asynchronous API calls. Make sure to put the redirect in the callback or promise resolution:

// Promises must be kept fetch('api/submitData', { method: 'POST', body: JSON.stringify(data), }) .then(response => response.json()) .then(result => { window.location.href = 'resultPage.html'; });