JavaScript document.URL 获取并解析当前地址

用 document.URL 读取当前文档地址。它返回一个只读字符串。如果需要分别获取路径、查询字符串或片段,请用 new URL(document.URL) 解析。

读取当前文档的完整地址

读取 document.URL 时不用括号。如果地址包含查询字符串或片段,也会一起返回。要跳转到其他地址,可使用 location.assign() 或给 location.href 赋值。DOM Standard · Document.URL Location 对象的 URL 属性

console.log(document.URL);
console.log(location.href);

拆分路径、查询参数和片段

pathname 返回路径,search 返回带开头 ? 的查询字符串,hash 返回带开头 # 的片段。没有查询或片段时,对应属性为空字符串。示例使用固定网址,以便在任何页面运行都得到相同结果。URL Standard · URL API

const current = new URL('https://example.com/guide?lang=ko&lang=en#example');
console.log(current.pathname);                // '/guide'
console.log(current.search);                  // '?lang=ko&lang=en'
console.log(current.hash);                    // '#example'
console.log(current.searchParams.get('lang')); // 'ko'
console.log(current.searchParams.getAll('lang')); // ['ko', 'en']
console.log(current.searchParams.get('page')); // null

const empty = new URL('https://example.com/guide?lang=');
console.log(empty.searchParams.get('lang')); // ''

searchParams.get('lang') 返回第一个值。参数缺失时返回 null。?lang= 会得到空字符串。要读取同名参数的所有值,可使用 getAll()。

解析文档中的相对路径时,可像 new URL('intro.html', document.baseURI) 这样传入基准地址。如果有 <base href>,baseURI 可能与 document.URL 不同。HTML Standard · Document base URL

用完整示例观察片段变化

将代码以 UTF-8 保存为 document-url.html,然后在浏览器中打开。点击前往下方区域的链接后,地址会加上 #details,hashchange 处理程序会更新输出。也可以用按钮重新读取。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>查看当前文档 URL</title>
</head>
<body>
<p><a href="#details">前往下方区域</a></p>
<button id="refresh" type="button">重新读取 URL</button>
<pre id="result" aria-live="polite"></pre>
<p id="details">下方区域</p>
<script>
const result = document.querySelector('#result');
const missing = "无";

function showURL() {
  const current = new URL(document.URL);
  const lang = current.searchParams.get('lang');
  result.textContent = [
    `完整 URL: ${document.URL}`,
    `路径: ${current.pathname}`,
    `查询: ${current.search || missing}`,
    `片段: ${current.hash || missing}`,
    `lang: ${lang === null ? missing : JSON.stringify(lang)}`
  ].join('\n');
}

document.querySelector('#refresh').addEventListener('click', showURL);
window.addEventListener('hashchange', showURL);
showURL();
</script>
</body>
</html>

本地文件地址以 file: 开头。在 #details 前插入 ?lang=ko 并重新打开地址,会看到 lang 显示为 "ko"。用 ?lang= 会显示 ""。删除参数会显示缺失提示。