在 JavaScript 中,获取当前网页的 URL 非常简单,主要通过 window.location 对象来实现,这个对象包含了当前页面的所有 URL 信息。

js如何获取当前网页的url
(图片来源网络,侵删)

下面我将从基础到高级,详细讲解如何获取 URL 的各个部分,并提供代码示例。

核心对象:window.location

window.location 是一个只读对象,它返回一个 Location 对象,该对象描述了当前文档的 URL,你可以把它看作一个包含了 URL 所有组成部分的“容器”。


获取完整的 URL

如果你想获取整个 URL 字符串,可以直接使用 window.location.href

示例:

js如何获取当前网页的url
(图片来源网络,侵删)
// 假设当前 URL 是: https://www.example.com:8080/path/to/page?query=1#section1
const fullUrl = window.location.href;
console.log(fullUrl); 
// 输出: "https://www.example.com:8080/path/to/page?query=1#section1"

获取 URL 的各个组成部分

window.location 对象提供了许多属性,让你可以方便地获取 URL 的特定部分。

属性 描述 示例 (基于上面的URL)
href 完整的 URL (等同于 toString()) "https://www.example.com:8080/path/to/page?query=1#section1"
protocol URL 的协议 (包括 ) "https:"
hostname 主机名 (域名) "www.example.com"
port 端口号 "8080"
pathname 路径部分 "/path/to/page"
search 查询字符串 (包括 ) "?query=1"
hash 锚点/片段标识符 (包括 ) "#section1"
host 主机名和端口号 "www.example.com:8080"

代码示例:

const currentUrl = window.location;
console.log("完整 URL:", currentUrl.href);
console.log("协议:", currentUrl.protocol);
console.log("主机名:", currentUrl.hostname);
console.log("端口号:", currentUrl.port);
console.log("路径:", currentUrl.pathname);
console.log("查询字符串:", currentUrl.search);
console.log("锚点:", currentUrl.hash);
console.log("主机 (含端口):", currentUrl.host);

输出结果:

完整 URL: https://www.example.com:8080/path/to/page?query=1#section1
协议: https:
主机名: www.example.com
端口号: 8080
路径: /path/to/page
查询字符串: ?query=1
锚点: #section1
主机 (含端口): www.example.com:8080

实用场景与示例

理解了如何获取 URL 各部分后,我们来看一些常见的应用场景。

js如何获取当前网页的url
(图片来源网络,侵删)

获取 URL 中的查询参数

这是一个非常常见的需求,比如根据 URL 中的 id 参数来加载不同的内容。

假设 URL 是:https://myapp.com/product?id=123&category=shoes

// 方法 1: 手动解析 (简单情况)
const queryString = window.location.search; // 得到 "?id=123&category=shoes"
const params = new URLSearchParams(queryString);
const id = params.get('id'); // 得到 "123"
const category = params.get('category'); // 得到 "shoes"
console.log(`产品ID: ${id}, 分类: ${category}`); // 输出: "产品ID: 123, 分类: shoes"
// 如果参数不存在,get() 会返回 null
const color = params.get('color');
console.log(color); // 输出: null
// 方法 2: 使用 URLSearchParams API (更现代、更推荐)
// 它提供了更多便利方法,如 getAll(), has(), keys(), values() 等
console.log(params.getAll('id')); // 如果有多个 'id',会返回数组
console.log(params.has('id'));    // 检查是否存在 'id' 参数,返回 true

判断当前是否在 HTTPS 下

if (window.location.protocol === 'https:') {
    console.log('当前页面是安全的 HTTPS 连接。');
} else {
    console.log('当前页面不是 HTTPS 连接。');
}

根据路径跳转到不同页面

const path = window.location.pathname;
if (path === '/login') {
    console.log('用户正在登录页面。');
} else if (path === '/dashboard') {
    console.log('用户正在访问仪表盘。');
}

location vs location.href

在大多数情况下,window.locationwindow.location.href 在读取时效果相同,因为 window.location 对象本身有一个 toString() 方法,会返回 href 的值。

console.log(window.location == window.location.href); // 在某些浏览器中可能返回 true
console.log(String(window.location) == window.location.href); // 总是 true

它们有一个关键区别:

  • window.location.href 是一个字符串,给它赋新值会导航到新的 URL。
  • window.location 是一个对象,给它赋新值也会导航到新的 URL,但更推荐使用 location.hreflocation.replace() 等方法来明确表达意图。

导航到新 URL 的几种方式:

// 1. 使用 href (最常用)
window.location.href = 'https://www.google.com';
// 2. 使用 assign() (效果与 href 相同,会添加到历史记录)
window.location.assign('https://www.google.com');
// 3. 使用 replace() (不会添加到历史记录,用户无法通过“后退”按钮返回)
window.location.replace('https://www.google.com');
// 4. 使用 reload() (刷新当前页面)
window.location.reload(); // 等同于按下 F5 或刷新按钮
window.location.reload(true); // 强制从服务器重新加载 (不使用缓存)

需求 代码 描述
获取完整 URL window.location.href 最常用,获取整个 URL 字符串。
获取协议 window.location.protocol https:
获取域名 window.location.hostname www.example.com
获取路径 window.location.pathname /path/to/page
获取查询参数 window.location.search ?id=123
解析查询参数 new URLSearchParams(window.location.search) 强烈推荐,用于处理 后面的键值对。
获取锚点 window.location.hash #section1
页面跳转 window.location.href = 'new-url' 导航到新页面,并保留历史记录。
页面替换 window.location.replace('new-url') 导航到新页面,不保留历史记录。

对于日常开发,window.location.hrefwindow.location.pathname 是最常用的,而处理 URL 查询参数时,URLSearchParams API 是现代 JavaScript 的标准做法,强烈推荐使用。