前端開發中頻繁需要構建完整 URL 或判斷當前環境(HTTP/HTTPS、開發/生產域名)。document.location 物件提供了標準化的屬性來獲取這些資訊。
var host = document.location.protocol + '//' + document.location.host;
| 屬性 | 返回值範例 | 說明 |
|---|---|---|
protocol | "https:"、"http:" | 包含冒號的協議名稱 |
host | "example.com:8080" | 域名 + 端口(若為標準端口則不含端口) |
hostname | "example.com" | 純域名,不含端口 |
port | "8080" | 端口號,標準端口返回空字串 |
origin | "https://example.com" | 推薦:直接獲取「協議+域名+端口」,等同於上述拼接結果 |
'//'?protocol 返回值已包含冒號("https:"),而標準 URL 格式要求協議後接雙斜線("https://")。因此需要手動添加 '//' 形成完整的 origin 部分。
location.origin// 簡潔、標準、無需拼接
const baseUrl = window.location.origin;
// 返回 "https://example.com:8080" 等完整來源
瀏覽器相容性:IE11+、所有現代瀏覽器均支援。若需支援極舊環境,可用上述拼接方式作為 Polyfill。
const apiBase = location.origin + '/api/v1';const isProd = location.hostname === 'www.myapp.com';origin 判斷同源策略const absoluteUrl = location.origin + relativePath;// 假設 URL: https://user:pass@sub.example.com:8080/path?query=1#hash
location.href // 完整 URL
location.protocol // "https:"
location.host // "sub.example.com:8080"
location.hostname // "sub.example.com"
location.port // "8080"
location.pathname // "/path"
location.search // "?query=1"
location.hash // "#hash"
location.origin // "https://sub.example.com:8080"
location.username // "user" (較少用)
location.password // "pass" (較少用)
總結:理解 document.location 各屬性差異,善用 location.origin 簡化代碼,是前端處理 URL 的基本功。