萬盛學電腦網

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

JavaScript 取得網頁 <base> 標籤 href 屬性值完整教學

前言

<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.hrefHTMLBaseElement解析後的絕對 URL (含協定、域名、路徑)標準 DOM API,可讀寫
baseEl.getAttribute('href')Element原始屬性值 (可能為相對路徑)未經瀏覽器解析
document.baseURIDocument文檔實際使用的基準 URL (唯讀)含 <base> 影響,無 <base> 時等於 location.href

實務應用場景

1. 動態構建相對路徑資源完整 URL

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

2. 檢測基準 URL 是否被篡改 (安全審計)

const expectedBase = 'https://www.example.com/';
if (document.baseURI !== expectedBase) {
  console.warn('基準 URL 異常,可能遭注入  標籤');
}

3. 單頁應用 (SPA) 路由基準控制

// 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 可安全解析相對路徑。

copyright © 萬盛學電腦網 all rights reserved