In JavaScript, you can redirect to a new page using several methods, most commonly by modifying the window.location
object. This allows you to navigate to a different URL programmatically.
The simplest way to redirect is by setting window.location.href
to the desired URL:
window.location.href = 'https://www.example.com';
Another way to redirect is by using window.location.assign()
, which behaves similarly to changing window.location.href
, but it allows for the new page to be added to the browser's history stack:
window.location.assign('https://www.example.com');
If you want to redirect without leaving a history entry (i.e., the user cannot hit the 'Back' button to return to the previous page), you can use window.location.replace()
:
window.location.replace('https://www.example.com');
All these methods perform a redirect, but the difference is in how they interact with the browser's history stack.
In summary, you can redirect users to a new page in JavaScript using window.location.href
, window.location.assign()
, or window.location.replace()
, depending on your needs regarding browser history.