用 JavaScript 的 location 获取当前 URL、域名和路径

用 window.location.href 读取当前地址,用 window.location.hostname 获取主机名,用 window.location.pathname 获取路径。Location 对象与当前文档的 URL 绑定。要解析其他地址,可以用 new URL(address)。

读取当前 URL 的各个部分

下表将示例地址 https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part 拆成多个部分。host 包含非默认端口,hostname 不含端口。省略端口或指定 HTTPS 的默认端口 443 时,port 为空字符串。属性定义见 HTML Living Standard。

属性 示例值 含义
href https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part 完整 URL
origin https://example.com:8080 HTTP(S) 协议方案、主机名和端口
protocol https: 包含末尾冒号的协议方案
host example.com:8080 主机名和非默认端口
hostname example.com 不含端口的主机名
port 8080 非默认端口号
pathname /path/page.html 不含查询和片段的路径
search ?lang=ko&tag=js&tag=dom&q=hello+world 包含问号的查询字符串
hash #part 包含井号的片段

解析地址与查询参数

在浏览器控制台中运行代码。前两行输出当前文档的地址和路径,其余是示例地址的解析结果。new URL() 解析地址时不会发送网络请求,也不会跳转页面。

const current = window.location;
console.log(current.href);
console.log(current.pathname);

const sample = new URL('https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part');
console.log(sample.host);
console.log(sample.hostname);
console.log(sample.searchParams.get('lang'));   // ko
console.log(sample.searchParams.get('tag'));    // js
console.log(sample.searchParams.getAll('tag')); // ['js', 'dom']
console.log(sample.searchParams.get('q'));      // hello world

search 包含 ? 和查询字符串。searchParams.get('tag') 返回第一个值 js,而 getAll('tag') 按顺序返回 ['js', 'dom']。键不存在时,get() 返回 null,getAll() 返回空数组。tag= 的第一个值为空字符串。查询中的 + 会解码为空格,因此 q 是 hello world。参见 URL Standard。

完整示例:比较当前 URL 和输入的 URL

将 HTML 以 UTF-8 编码保存为 location-example.html 并在浏览器中打开。「解析 URL」读取输入框中的绝对地址。「当前页面的 URL」复制并解析已打开文档的地址。「重置」恢复示例地址。

<!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>
<label for="address">要解析的绝对 URL</label>
<input id="address" type="url" size="60" value="https://example.com:8080/path/page.html?lang=ko&amp;tag=js&amp;tag=dom&amp;q=hello+world#part">
<button id="parse" type="button">解析 URL</button>
<button id="current" type="button">当前页面的 URL</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const address = document.querySelector('#address');
const output = document.querySelector('#output');

function show(value) {
  try {
    const url = new URL(value);
    output.textContent = [
      `href: ${url.href}`,
      `origin: ${url.origin}`,
      `protocol: ${url.protocol}`,
      `host: ${url.host}`,
      `hostname: ${url.hostname}`,
      `port: ${url.port || "(无)"}`,
      `pathname: ${url.pathname}`,
      `search: ${url.search || "(无)"}`,
      `hash: ${url.hash || "(无)"}`,
      `lang: ${url.searchParams.get('lang') ?? "(无)"}`,
      `tag: ${JSON.stringify(url.searchParams.getAll('tag'))}`,
      `q: ${url.searchParams.get('q') ?? "(无)"}`,
    ].join('\n');
  } catch (error) {
    output.textContent = "请输入有效的绝对 URL。";
  }
}

document.querySelector('#parse').addEventListener('click', () => show(address.value));
document.querySelector('#current').addEventListener('click', () => {
  address.value = window.location.href;
  show(address.value);
});
document.querySelector('#reset').addEventListener('click', () => {
  address.value = 'https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part';
  show(address.value);
});
show(address.value);
</script>
</body>
</html>

在初始输出中,host 包含 :8080,hostname 不包含。tag 数组显示两个值,q 含有空格。只输入 /path/page.html 会因没有基准地址而报错。解析相对路径时可使用 new URL(relativePath, baseURL)。从磁盘打开文件时,当前地址以 file: 开头。

区分读取地址与页面跳转

给 location.href 赋值或调用 location.assign(url) 会跳转。location.replace(url) 还会替换当前历史记录条目,因此按返回键会跳过被替换的页面。这个示例只显示属性。用于跳转前,请检查地址的协议方案和源是否在项目的允许范围内。参见 HTML Living Standard。