How to set window.location using TypeScript

avatar

Borislav Hadzhiev

Last updated: Apr 1, 2022

banner

Photo from Unsplash

Set window.location using TypeScript #

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.

index.html
<!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.

src/index.ts
const btn = document.getElementById('btn'); btn?.addEventListener('click', function onClick() { window.location.href = 'https://google.com'; });
If you load the page and click on the button, you will navigate to the webpage you assigned to the property.

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.

src/index.ts
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.