In JavaScript, you can achieve redirection by modifying the window.location
object. Here are a few common methods used to redirect to a different URL:
window.location.href
This is the most common way to redirect a page. You simply assign the new URL to window.location.href
. For example:
window.location.href = "https://www.example.com";
window.location.assign()
This method causes the window to load and display the document at the URL specified. You can use it like this:
window.location.assign("https://www.example.com");
window.location.replace()
Unlike window.location.href
and window.location.assign()
which keep the previous page in session history (allowing you to go back to it with the back button), window.location.replace()
removes the URL of the current document from the document history, meaning you can't use the back button to return to the original document.
window.location.replace("https://www.example.com");
window.location
You can also just assign a URL directly to window.location
. This behaves similarly to setting window.location.href
:
window.location = "https://www.example.com";
Choose the method that best fits your needs based on whether you need to keep the history or not, and always test redirection actions to ensure they work as expected in your application's context.