How do I redirect to another webpage?
To perform a webpage redirect in JavaScript, you can utilize the built-in object window.location.href
:
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
:
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
:
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:
jQuery-based Redirection
If you're a jQuery aficionado, here's the equivalent, though pure JavaScript is more efficient:
Back in Time
Want to revert to the previous page you were on?
Topmost Frame
With top.location
, you can change the location of the topmost frame:
The Obsolete window.navigate
Once supported in legacy versions of IE, window.navigate
is now outdated:
Preserving HTTP_REFERER
To keep HTTP_REFERER
in IE8 or before, create and click an anchor element:
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:
Auto-redirect
When you need to redirect after certain events or after a brief delay:
SPA Routing
For Single-Page Applications, client-side routing without full page refreshes can be a boon:
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:
Deferred Redirects
Tricky business when redirecting after asynchronous API calls. Make sure to put the redirect in the callback or promise resolution:
Was this article helpful?