| 屬性 | 範例值 (假設 URL: https://user:pass@sub.example.com:8080/path/page.html?query=1#hash) | 說明 |
|---|---|---|
href | 完整 URL | 完整網址,可讀寫(寫入會導向) |
protocol | "https:" | 協定方案(含冒號) |
host | "sub.example.com:8080" | 主機名 + 埠號(若為預設埠則不含埠) |
hostname | "sub.example.com" | 純主機名(無埠號) |
port | "8080" | 埠號字串(預設埠為空字串) |
pathname | "/path/page.html" | 路徑(以 / 開頭) |
search | "?query=1" | 查詢字串(含 ?) |
hash | "#hash" | 錨點(含 #) |
origin | "https://sub.example.com:8080" | 協定+主機+埠(唯讀,跨域判斷關鍵) |
// 1. 當前完整網址
const fullUrl = window.location.href;
// 2. 當前域名(含子域名,不含埠)
const domain = window.location.hostname;
// 3. 當前域名 + 埠(同源策略判斷用)
const host = window.location.host;
// 4. 當前頁面路徑
const path = window.location.pathname;
// 5. 當前查詢參數物件
const params = new URLSearchParams(window.location.search);
const page = params.get("page"); // "1"
// 6. 當前錨點
const hash = window.location.hash; // "#section2"
// 7. 同源檢查
function isSameOrigin(url) {
const a = document.createElement("a");
a.href = url;
return a.origin === location.origin;
}
document.domain 僅能**放寬**同源限制(如 a.example.com 與 b.example.com 同設為 example.com 即可互通),**無法獲取完整域名資訊**,且**已棄用**(Deprecated),現代瀏覽器將移除支援,**請勿在新專案使用**。
// 同源情況下
top.location.href; // 頂層視窗完整網址
parent.document.location; // 父視窗 Location 物件
top.location.hostname; // 頂層主機名
// 跨域:無法直接存取,需用 postMessage 通訊
const url = new URL("https://sub.example.com:8080/path?query=1#hash");
console.log(url.hostname); // "sub.example.com"
console.log(url.searchParams.get("query")); // "1"
url.searchParams.set("page", "2");
console.log(url.href); // 更新後的完整 URL