<base> 標籤指定頁面所有相對連結的基準 URL。JavaScript 可透過 document.querySelector('base') 或 document.getElementById 取得其 href 屬性。本文示範基本用法與注意事項。
// 方式 1: ID 選取 (推薦)
const baseUrl = document.getElementById('baseId').href;
// 方式 2: 標籤選取 (頁面僅一個 base)
const baseUrl = document.querySelector('base').href;
// 方式 3: document.baseURI (唯讀, 含完整解析後的基準 URL)
const baseUrl = document.baseURI;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base id="pageBase" href="https://www.example.com/subdir/">
<title>Base URL 取得範例</title>
</head>
<body>
<p>Base URL: <span id="output"></span></p>
<script>
// 方法 1: ID 取得
const baseEl = document.getElementById('pageBase');
console.log('ID href:', baseEl.href); // 完整解析後的絕對 URL
// 方法 2: document.baseURI (含查詢字串、雜湊)
console.log('document.baseURI:', document.baseURI);
// 顯示在頁面
document.getElementById('output').textContent = baseEl.href;
</script>
</body>
</html>
| 屬性/方法 | 來源 | 回傳值 | 備註 |
|---|---|---|---|
| baseEl.href | HTMLBaseElement | 解析後的絕對 URL (含協定、域名、路徑) | 標準 DOM API,可讀寫 |
| baseEl.getAttribute('href') | Element | 原始屬性值 (可能為相對路徑) | 未經瀏覽器解析 |
| document.baseURI | Document | 文檔實際使用的基準 URL (唯讀) | 含 <base> 影響,無 <base> 時等於 location.href |
function resolveUrl(relativePath) {
const base = document.querySelector('base')?.href || location.origin + '/';
return new URL(relativePath, base).href;
}
console.log(resolveUrl('images/logo.png')); // https://www.example.com/subdir/images/logo.png
const expectedBase = 'https://www.example.com/';
if (document.baseURI !== expectedBase) {
console.warn('基準 URL 異常,可能遭注入 標籤');
}
// Vue/React 路由 base 配置對應
// -> document.baseURI = "https://domain.com/app/"
router.push('/user/1'); // 實際導航至 /app/user/1
<base>,多個僅第一個生效。<head> 內,且在所有相對連結之前。<a>, <link>, <img>, <script>, <form action> 等所有相對 URL。<a href="#section"> 仍相對於 base href 解析,非當前頁面 URL。取得 <base> 的 href 最直接用 document.getElementById('id').href (回傳解析後絕對 URL);需文檔實際生效基準用 document.baseURI (唯讀)。善用 URL 建構子配合基準 URL 可安全解析相對路徑。