The window.location object represents the current URL location of the document. Modifying its properties or calling its methods navigates the browser to new URLs or reloads the page.
flowchart LR
URLStr["https://kodersolution.com:8080/tutorials/js?topic=dom#section1"] --> Proto["protocol: 'https:'"]
URLStr --> Host["host: 'kodersolution.com:8080'"]
URLStr --> Path["pathname: '/tutorials/js'"]
URLStr --> Search["search: '?topic=dom'"]
URLStr --> Hash["hash: '#section1'"]
| API | Type / Action | Description |
|---|---|---|
location.href |
Property (String) | Gets or sets full URL string (Triggers navigation). |
location.hostname |
Property (String) | Domain name without port ("kodersolution.com"). |
location.pathname |
Property (String) | Path section of URL following domain. |
location.search |
Property (String) | Query string parameter starting with ?. |
location.assign(url) |
Method | Navigates to new URL (Adds entry to browser history). |
location.replace(url) |
Method | Replaces current URL in history (Cannot click Back). |
location.reload() |
Method | Reloads current page document. |
// Demonstrating location inspection, URLSearchParams, and redirection
// 1. Inspecting Current Location Parts
console.log(`Current Protocol: ${location.protocol}`);
console.log(`Current Hostname: ${location.hostname}`);
console.log(`Current Pathname: ${location.pathname}`);
// 2. Parsing Query Parameters with URLSearchParams API
const queryParams = new URLSearchParams(location.search);
const category = queryParams.get("category"); // e.g. "?category=javascript"
console.log(`Parsed Category Query Param: ${category}`);
// 3. Navigation Helpers
function navigateToLogin() {
// Option A: Standard Navigation (User can click Back button)
location.assign("/login");
// Option B: Redirection without back history entry (Authentication redirects)
// location.replace("/login");
}
location.replace() for Post-Login Redirects: Use location.replace() after successful login or logout so users cannot click the browser Back button to re-access unauthenticated pages.URLSearchParams for Query Strings: Use new URLSearchParams(location.search) to parse and extract query parameters cleanly instead of using custom regex.location.href to prevent Open Redirect security vulnerabilities.What is the operational difference between location.assign(url) and location.replace(url)?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.