JavaScript Window Location
14 April 2025 | Category: JavaScript
The window.location
object in JavaScript is used to get or change the current URL of the browser. It plays a key role in redirecting pages, reloading, and navigating through different parts of a website.
đ What is window.location
?
- It is a property of the
window
object. - It holds information about the current URL.
- It also provides methods to redirect or reload the page.
console.log(window.location);
You can also just use location
because window
is global.
đš Common location
Properties
Property | Description | Example Output |
---|---|---|
location.href | The full URL | https://example.com/path?query=123 |
location.hostname | The domain name only | example.com |
location.pathname | The path of the URL | /path |
location.protocol | The protocol used (http/https) | https: |
location.port | The port number (if any) | 80 , 443 , or empty |
location.search | The query string (after ? ) | ?query=123 |
location.hash | The anchor part (after # ) | #section1 |
đ¸ Example: Log URL Details
console.log("Full URL:", location.href);
console.log("Domain:", location.hostname);
console.log("Path:", location.pathname);
console.log("Protocol:", location.protocol);
console.log("Query String:", location.search);
console.log("Hash:", location.hash);
đ Changing the Page URL
You can use these to redirect the browser to a new page.
â
location.href
location.href = "https://google.com"; // Redirect to Google
â
location.assign()
location.assign("https://example.com"); // Also redirects
â
location.replace()
location.replace("https://example.com");
// Redirects, but doesn't keep history (can't go back)
đ Reloading the Page
location.reload(); // Reloads the current page
You can also use
location.reload(true)
in older browsers to force reload from the server (not cache).
đ Example Mini App: Redirect Button
<button onclick="goToPage()">Go to YouTube</button>
<script>
function goToPage() {
location.href = "https://youtube.com";
}
</script>
â Summary
Task | Code Example |
---|---|
Get full URL | location.href |
Redirect to a page | location.href = "url" |
Force redirect | location.replace("url") |
Reload the page | location.reload() |
Get query string | location.search |
Get page path | location.pathname |