window.location (read-only) trả về Location object chứa thông tin URL hiện tại.
Properties chính
| Property | Mô tả |
|---|---|
href | Full URL string |
protocol | Scheme + ':' (https:) |
host | hostname + ':' + port |
hostname | Domain (không port) |
port | Port number |
pathname | Path (bắt đầu bằng /) |
search | Query string (bắt đầu bằng ?) |
hash | Fragment (bắt đầu bằng #) |
username, password | Credentials trong URL (hiếm dùng) |
Ví dụ
const hostname = location.hostname; // "www.tutorialspoint.com" const path = location.pathname; // "/ajax/index.htm" console.log(hostname, path);
Modern: URL API (ES2015+)
const url = new URL('https://user:pass@example.com:8080/path?query=1#hash');
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.searchParams.get('query')); // "1"
Khuyến nghị: Dùng URL constructor cho parsing URL bất kỳ (không chỉ current page). location chỉ cho current document.