window.location 是前端獲取/操作 URL 的核心 API。本文整理所有屬性與方法,附帶實戰工具函數、URLSearchParams 現代用法、路由守衛場景應用,做你案頭必備速查手冊。
| 屬性 | 返回值示例 | 說明 | 可寫入 |
|---|---|---|---|
href | "https://example.com:8080/path/page.html?query=1#hash" | 完整 URL | ✅ 整體跳轉 |
protocol | "https:" | 協議(含冒號) | ✅ |
host | "example.com:8080" | 主機 + 端口 | ✅ |
hostname | "example.com" | 主機名(無端口) | ✅ |
port | "8080" | 端口號(默認端口返回空串) | ✅ |
pathname | "/path/page.html" | 路徑(以 / 開頭) | ✅ |
search | "?query=1" | 查詢字符串(含 ?) | ✅ |
hash | "#hash" | 錨點(含 #) | ✅ |
origin | "https://example.com:8080" | 協議+主機+端口(只讀) | ❌ |
// 獲取單個參數
function getQueryParam(name: string, url = window.location.href): string | null {
const params = new URLSearchParams(new URL(url).search);
return params.get(name);
}
// 獲取所有參數為對象
function getAllQueryParams(url = window.location.href): Record {
const params = new URLSearchParams(new URL(url).search);
const obj: Record = {};
for (const [k, v] of params) obj[k] = v;
return obj;
}
// 設置/刪除參數並生成新 URL
function setQueryParam(name: string, value: string | null, url = window.location.href): string {
const u = new URL(url);
if (value === null) u.searchParams.delete(name);
else u.searchParams.set(name, value);
return u.toString();
}
function getHashParams(): Record {
const hash = window.location.hash.slice(1); // 移除 #
const [path, search = ''] = hash.split('?');
const params = new URLSearchParams(search);
const obj: Record = { _path: path };
for (const [k, v] of params) obj[k] = v;
return obj;
}
function getRelativeUrl(url = window.location.href): string {
return new URL(url).pathname + new URL(url).search + new URL(url).hash;
}
function isSameOrigin(url: string): boolean {
try {
const a = new URL(url, window.location.origin);
return a.origin === window.location.origin;
} catch {
return false;
}
}
| 方法 | 行為 | 歷史記錄 | 適用場景 |
|---|---|---|---|
location.href = url | 跳轉 | 新增記錄 | 普通跳轉 |
location.assign(url) | 跳轉 | 新增記錄 | 語義化、可被攔截 |
location.replace(url) | 替換當前 | 替換記錄 | 登錄後跳轉、防止回退 |
location.reload() | 重新加載 | 保持 | 刷新頁面 |
history.pushState() | 無刷新改變 URL | 新增記錄 | SPA 路由 |
history.replaceState() | 無刷新替換 URL | 替換記錄 | 模態框打開時更新 URL |
// 推薦:標準、語義清晰
location.reload();
// 強制從服務器獲取(繞過緩存)
location.reload(true); // 非標準,僅部分瀏覽器支持
// 通用強制刷新
location.href = location.href.split('?')[0] + '?v=' + Date.now();
// 歷史記錄導航
history.go(0); // 刷新
history.back(); // 後退
history.forward(); // 前進
history.go(-2); // 後退兩步
// 路由守衛中攔截未登錄訪問
function requireAuth(toPath = window.location.pathname) {
const loginUrl = '/login';
const redirectParam = encodeURIComponent(toPath + window.location.search);
location.replace(`${loginUrl}?redirect=${redirectParam}`);
}
// 登錄成功後恢復
function redirectAfterLogin(defaultPath = '/') {
const params = new URLSearchParams(window.location.search);
const redirect = params.get('redirect') || defaultPath;
location.replace(redirect); // replace 防止回退到登錄頁
}
location.href = userInput 可能導致 javascript:alert(1) 執行 → 嚴格驗證協議為 http/httpsredirect 參數未驗證域名 → 魚叉式釣魚攻擊 → 白名單驗證 或 僅允許相對路徑URL 構造器自動編碼,拼接字符串易出錯 → 統一用 new URL() / URLSearchParamspathname、search、hash、origin 覆蓋 99% 需求URLSearchParamsnew URL(),自動編碼、自動處理相對路徑、類型安全replace 替換歷史,assign/href 新增歷史,pushState 無刷新將這份速查表存入項目 docs/cheatsheets/location.md,下次操作 URL 直接 Ctrl+F,零心智負擔。