How To Navigate To A New Page Using JavaScript
How do you programmatically navigate to a new page or URL when coding in JavaScript?
JavaScript has a built-in way to do this using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window
interface has access to the Location
object that can be used via window.location
.
Included in the Location
interface is a href
value, which represents a USVString containing the whole URL for a page.
This value can also be assigned a different and new URL:
window.location.href = "https://www.google.com"
By setting a new value for location.href, the page will navigate to the new URL you provide.
To quickly test this, open the developer tools in your favorite browser and execute the above code in the JavaScript console. The page should redirect to the Google homepage.
By navigating to a new page in this manner, the original page will stay in the session History
. Therefore, users will be able to use the back button in their browser to return to the original page.
For more information on the browser support for the location.href
method, see its MDN web docs page.
Thanks for reading and happy coding!