Borislav Hadzhiev
Fri Apr 01 2022·1 min read
Photo by Solé Bicycles
Use the window.location.href
property to set the window.location
in
TypeScript, e.g. window.location.href = 'https://google.com'
. Setting the
location.href
property causes the browser to navigate to the provided URL.
Here is the index.html
file for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Change location</button> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
const btn = document.getElementById('btn'); btn?.addEventListener('click', function onClick() { window.location.href = 'https://google.com'; });
The location.href property returns a string containing the whole URL and allows the href to be updated.
When you set the value of window.location.href
, the browser navigates to the
provided URL.
You might also use the window.location.assign method to achieve the same result.
const btn = document.getElementById('btn'); console.log(window.location.href); btn?.addEventListener('click', function onClick() { window.location.assign('https://google.com'); });
The window.location.assign()
method enables us to navigate to a new page.
The method takes a URL string as a parameter and navigates to the page.
Similar methods to assign
include:
window.location.reload()
- reloads the current URL, like the refresh button.window.location.replace()
- redirects to the provided URL. The difference
from the assign()
method is that when using the replace()
method, the
current page is not saved in session history, so users are not able to use the
back button to navigate to it.If you need to check out all of the properties on the location object, here is a link from the MDN docs.