In JavaScript, the window.location
object lets you get the current page URL or redirect the browser to a different page. It's one of the easiest and most powerful ways to work with URLs in your web applications.
In this article, you'll learn how to get, set, and change URLs using window.location
, with clear examples and practical use cases.
What is window.location
?
window.location
is a built-in JavaScript object that contains information about the current URL. You can also use it to navigate to a different page.
Get the Current URL
What it does:
This prints the full current URL (including protocol, domain, path, etc.).
Other Useful window.location
Properties
You can access specific parts of the URL:
Property | Description | Example Output |
---|---|---|
href | Full URL | https://example.com/page?x=10 |
protocol | Protocol used | https: |
hostname | Domain name | example.com |
pathname | Path after domain | /page |
search | Query string | ?x=10 |
hash | Anchor (if any) | #section2 |
Change the URL (Redirect)
You can redirect the user to another page using window.location.href
:
What it does:
Takes the user to the new URL, just like clicking a link.
Use window.location.assign()
-
Works like setting
href
-
Adds the new page to the browser history (user can go back)
Use window.location.replace()
-
Also redirects, but does not keep the current page in the history
-
Good for login/logout flows or preventing users from going back
Reload the Page
-
Reloads the current page (like pressing the refresh button)
-
Optional:
window.location.reload(true)
forces a reload from the server (some browsers may ignore this)
Common Use Cases
-
Redirect users after login or logout
-
Get query parameters from the URL
-
Navigate between pages in a single-page app (SPA)
-
Refresh the page after a specific action
Summary
The window.location
object gives you full control over the browser's address bar. You can read the current URL, change it, or reload the page easily — making it an essential tool for any web developer.
Key Points:
-
Use
window.location.href
to get or change the URL -
Use
assign()
to redirect with history -
Use
replace()
to redirect without history -
Use
reload()
to refresh the page