
JavaScript redirect
To redirect a user to a different web page using JavaScript, you can use the window.location
object. Here are a few ways to accomplish a redirect:
- Using the
assign()
method:
window.location.assign("https://www.example.com");
This method assigns a new URL to the current window, effectively redirecting the user to the specified URL.
- Using the
replace()
method:
window.location.replace("https://www.example.com");
This method replaces the current URL in the browser’s history with the new URL. The user is redirected to the new URL without the ability to navigate back to the previous page.
- Directly modifying the
href
property:
window.location.href = "https://www.example.com";
Assigning a new URL directly to the href
property of window.location
also triggers a redirect.
All of the above methods will cause the browser to navigate to the specified URL, loading the new page and potentially leaving the current page. It’s important to note that once a redirect is triggered, the remaining code in the current script will not be executed.
Remember to include the full URL (including the protocol, e.g., “https://”) in the redirect target for reliable navigation.