萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取當前頁面 URL 路徑、協議、參數、主機等完整屬性指南

本文在 71155 基礎上深化,系統整理 window.location、document.URL、document.referrer 等所有獲取 URL 的途徑,對比差異,提供現代 URL/URLSearchParams API 實戰模式,並補充服務端模板變量混用場景。

一、客戶端獲取 URL 的所有途徑

API類型示例值說明
window.location.href字符串"https://example.com:8080/path?query=1#hash"完整 URL,可讀寫,寫入觸發跳轉
window.locationLocation 對象同 href隱式調用 toString() 等同 href
document.URL字符串同 href只讀,文檔初始 URL,若 history.pushState 改變 URL 不會更新
document.locationLocation/字符串同 href別名,建議統一用 window.location
self.locationLocation同 href窗口自我引用,iframe 中指向 iframe 自身
top.locationLocation頂層窗口 URL跨域 iframe 受限,同源可訪問
parent.locationLocation父窗口 URL同上

二、Location 對象屬性完整解析 (同 71155,此處精簡)


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" (只讀)

三、現代 URL 解析 API (推薦替代手動解析)

1. URL 構造器 (解析/構造/修改)


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"

2. 相對 URL 解析 (基於基準 URL)


// 相對路徑解析
const abs = new URL('../api/users', 'https://example.com/admin/page.html');
// abs.href === "https://example.com/api/users"

3. 當前頁面 URL 解析


const current = new URL(window.location.href);
// 等價於 new URL(window.location) (構造器接受 Location 對象)

四、服務端模板變量混用場景 (JSP/Thymeleaf/Freemarker 等)

原文片段分析


// 原文混合了 JSP 模板語法
var url = "<%=request.getRequestURI()%>"; // 服務端渲染為 "/context/path"
alert(url);

正確區分:服務端 vs 客戶端

來源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.href
  • thisHREF = document.location.href 等冗余變量 → 直接用 location 對象屬性
  • split('/') 手動解析 → new URL() / URLSearchParams
  • JSP 模板變量 <%=...%> → 規範為 window.APP_CONFIG 注入

七、總結

  1. 客戶端:只用 window.location (Location 對象) + new URL() / URLSearchParams
  2. 服務端模板:注入最小配置對象 window.APP_CONFIG,避免模板語法散落 JS 邏輯中
  3. 跨框架通信:同源用 top.location/parent.location,跨域用 postMessage
  4. 安全:用戶輸入進 URL 必經 new URL() 驗證協議/域名

將 URL API 內化為肌肉記憶,URL 解析構造不再寫正則、不再拼字符串、不再踩編碼坑。

copyright © 萬盛學電腦網 all rights reserved