本文在 window.location、document.URL、document.referrer 等所有獲取 URL 的途徑,對比差異,提供現代 URL/URLSearchParams API 實戰模式,並補充服務端模板變量混用場景。
| API | 類型 | 示例值 | 說明 |
|---|---|---|---|
window.location.href | 字符串 | "https://example.com:8080/path?query=1#hash" | 完整 URL,可讀寫,寫入觸發跳轉 |
window.location | Location 對象 | 同 href | 隱式調用 toString() 等同 href |
document.URL | 字符串 | 同 href | 只讀,文檔初始 URL,若 history.pushState 改變 URL 不會更新 |
document.location | Location/字符串 | 同 href | 別名,建議統一用 window.location |
self.location | Location | 同 href | 窗口自我引用,iframe 中指向 iframe 自身 |
top.location | Location | 頂層窗口 URL | 跨域 iframe 受限,同源可訪問 |
parent.location | Location | 父窗口 URL | 同上 |
const loc = window.location;
loc.protocol; // "https:"
loc.host; // "example.com:8080"
loc.hostname; // "example.com"
loc.port; // "8080" (默認端口為空串)
loc.pathname; // "/path/page.html"
loc.search; // "?query=1&foo=bar"
loc.hash; // "#section1"
loc.origin; // "https://example.com:8080" (只讀)
const url = new URL('https://example.com:8080/path/page.html?query=1#hash');
// 讀取
url.protocol; // "https:"
url.host; // "example.com:8080"
url.hostname; // "example.com"
url.port; // "8080"
url.pathname; // "/path/page.html"
url.search; // "?query=1"
url.hash; // "#hash"
url.origin; // "https://example.com:8080"
// 參數操作 (URLSearchParams)
url.searchParams.get('query'); // "1"
url.searchParams.set('query', '2');
url.searchParams.append('tag', 'js');
url.searchParams.delete('foo');
url.searchParams.has('query'); // true
url.searchParams.toString(); // "query=2&tag=js"
// 修改路徑/哈希
url.pathname = '/new/path';
url.hash = 'section2';
// 序列化
url.toString(); // "https://example.com:8080/new/path?query=2&tag=js#section2"
// 相對路徑解析
const abs = new URL('../api/users', 'https://example.com/admin/page.html');
// abs.href === "https://example.com/api/users"
const current = new URL(window.location.href);
// 等價於 new URL(window.location) (構造器接受 Location 對象)
// 原文混合了 JSP 模板語法
var url = "<%=request.getRequestURI()%>"; // 服務端渲染為 "/context/path"
alert(url);
| 來源 | API | 獲取內容 | 可用階段 |
|---|---|---|---|
| 服務端 (JSP) | request.getRequestURI() | /app/user/profile (無協議/主機/查詢參數) | 模板渲染時 |
| 服務端 | request.getRequestURL() | https://host:port/app/user/profile (含協議/主機/端口) | 模板渲染時 |
| 服務端 | request.getQueryString() | tab=info&id=123 (無 ?) | 模板渲染時 |
| 服務端 | request.getServletPath() | /user/profile (不含 ContextPath) | 模板渲染時 |
| 客戶端 | window.location.pathname | /app/user/profile | 瀏覽器運行時 |
| 客戶端 | window.location.search | ?tab=info&id=123 | 瀏覽器運行時 |
<script>
// 服務端渲染注入最小必要配置
window.APP_CONFIG = {
basePath: "<%=request.getContextPath()%>", // "/app"
apiBase: "<%=request.getScheme()%>://<%=request.getServerName()%>:<%=request.getServerPort()%><%=request.getContextPath()%>/api",
currentUser: <%=JSON.stringify(userDto)%> // 複雜對象用 JSON 序列化
};
</script>
// 客戶端統一使用
const apiUrl = `${APP_CONFIG.apiBase}/users`;
// 獲取當前頁面相對路徑 (含查詢/哈希)
export function getCurrentRelativeUrl(): string {
return window.location.pathname + window.location.search + window.location.hash;
}
// 獲取不含查詢參數的路徑
export function getCleanPath(): string {
return window.location.pathname;
}
// 判斷是否為指定路徑 (支持通配符)
export function isPath(pattern: string): boolean {
const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
return regex.test(window.location.pathname);
}
// 構建帶參數的新 URL (不跳轉)
export function buildUrl(path: string, params: Record): string {
const url = new URL(path, window.location.origin);
Object.entries(params).forEach(([k, v]) => {
if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
});
return url.toString();
}
// 安全跳轉 (防開放重定向)
export function safeRedirect(url: string, allowedHosts: string[] = [window.location.hostname]): void {
try {
const target = new URL(url, window.location.origin);
if (allowedHosts.includes(target.hostname)) {
window.location.href = target.toString();
} else {
console.error('阻止跳轉至非信任域:', target.hostname);
}
} catch {
console.error('無效 URL:', url);
}
}
document.URL / document.location.href → 統一用 window.location.hrefthisHREF = document.location.href 等冗余變量 → 直接用 location 對象屬性split('/') 手動解析 → new URL() / URLSearchParams<%=...%> → 規範為 window.APP_CONFIG 注入window.location (Location 對象) + new URL() / URLSearchParamswindow.APP_CONFIG,避免模板語法散落 JS 邏輯中top.location/parent.location,跨域用 postMessagenew URL() 驗證協議/域名將 URL API 內化為肌肉記憶,URL 解析構造不再寫正則、不再拼字符串、不再踩編碼坑。