window.location 物件提供了豐富的屬性與方法,可解析、操作當前頁面的 URL。本文詳細說明各屬性用途、回傳值範例,並提供取得查詢參數的實用工具函數。
scheme://host:port/path?query#fragment
https://www.example.com:8080/path/page.html?id=123&name=test#section1
| 屬性 | 說明 | 範例回傳值 |
|---|---|---|
href | 完整 URL | "https://www.example.com:8080/path/page.html?id=123#section1" |
protocol | 協定(含冒號) | "https:" |
host | 主機名 + 埠號 | "www.example.com:8080" |
hostname | 主機名(無埠號) | "www.example.com" |
port | 埠號(預設埠為空字串) | "8080" / "" |
pathname | 路徑(以 / 開頭) | "/path/page.html" |
search | 查詢字串(含 ?) | "?id=123&name=test" |
hash | 錨點(含 #) | "#section1" |
origin | 協定+主機+埠(唯讀) | "https://www.example.com:8080" |
const fullUrl = window.location.href;
/**
* 將 query string 解析為物件
* @param {string} [query=window.location.search] - 查詢字串
* @returns {Object} 參數鍵值對
*/
function parseQueryString(query = window.location.search) {
const params = {};
const search = query.startsWith('?') ? query.slice(1) : query;
if (!search) return params;
search.split('&').forEach(pair => {
const [key, value] = pair.split('=').map(decodeURIComponent);
if (key in params) {
// 同名參數轉為陣列
params[key] = [].concat(params[key], value);
} else {
params[key] = value;
}
});
return params;
}
// 使用範例:?id=123&tag=js&tag=web
const qs = parseQueryString();
console.log(qs.id); // "123"
console.log(qs.tag); // ["js", "web"]
URLSearchParams)const params = new URLSearchParams(window.location.search);
const id = params.get('id'); // "123"
const tags = params.getAll('tag'); // ["js", "web"]
const hasName = params.has('name'); // false
URLSearchParams 享有廣泛瀏覽器支援(IE 需 polyfill),是現代專案首選。
// 替換當前歷史記錄
history.replaceState(null, '', '?page=2&sort=desc');
// 新增歷史記錄
history.pushState(null, '', '/article/123');
location.href = 'https://new-url.com'; // 導向(保留歷史)
location.replace('https://new-url.com'); // 導向(不保留歷史,無法回上頁)
location.reload(); // 重新載入
location.assign('/new-path'); // 同 href,但可攔截
port 屬性:若使用預設埠(HTTP:80, HTTPS:443),回傳空字串 "" 而非數字。origin 為唯讀屬性,無法直接指派。hash 不會觸發頁面重載,適合單頁應用路由。parent.location 會受同源策略限制。善用 window.location 與 URLSearchParams,能輕鬆處理 URL 解析、參數傳遞與頁面導向需求。