How to Redirect to Another Page in JavaScript Quickly
To redirect to another page in JavaScript, use
window.location.href = 'URL' to change the current page or window.location.replace('URL') to replace the current page without saving it in history. Both methods navigate the browser to the new URL.Syntax
There are two common ways to redirect in JavaScript:
window.location.href = 'URL': Changes the current page and saves the previous page in browser history.window.location.replace('URL'): Changes the current page but does not save the previous page in history, so the back button won't return to it.
javascript
window.location.href = 'https://example.com'; // or window.location.replace('https://example.com');
Example
This example shows how to redirect the user to "https://example.com" after 3 seconds using window.location.href.
javascript
setTimeout(() => { window.location.href = 'https://example.com'; }, 3000);
Output
After 3 seconds, the browser navigates to https://example.com
Common Pitfalls
Some common mistakes when redirecting include:
- Using
window.location.hrefwhen you want to prevent the user from going back, instead usewindow.location.replace(). - Trying to redirect before the page fully loads, which might cause unexpected behavior.
- Not specifying the full URL or a correct relative path, leading to navigation errors.
javascript
/* Wrong: user can go back */ window.location.href = 'https://example.com'; /* Right: user cannot go back */ window.location.replace('https://example.com');
Quick Reference
| Method | Description | Back Button Behavior |
|---|---|---|
| window.location.href = 'URL' | Redirects to URL and saves current page in history | Back button returns to previous page |
| window.location.replace('URL') | Redirects to URL without saving current page | Back button does NOT return to previous page |
Key Takeaways
Use window.location.href to redirect and keep the previous page in history.
Use window.location.replace to redirect without allowing back navigation.
Always specify a full or correct relative URL to avoid navigation errors.
Delaying redirect until page load can prevent unexpected issues.
Test redirects in different browsers to ensure consistent behavior.