1. 为什么需要获取当前页面URL?
在Web开发中,获取当前页面URL是一个基础但极其重要的操作。你可能遇到过这些场景:需要根据URL参数动态渲染页面内容、实现页面跳转后的状态保持、或者做用户行为分析统计。这些都是基于当前URL信息的操作。
举个例子,电商网站的商品详情页通常会把商品ID放在URL里,比如example.com/product?id=123。前端代码需要提取这个ID才能向后台请求对应的商品数据。又或者,在做单页应用(SPA)路由时,我们需要监听URL变化来切换不同的组件视图。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 获取URL的几种核心方法
2.1 使用window.location对象
这是最直接的方式。window.location对象包含了当前页面的完整URL信息,它的各个属性可以获取URL的不同部分:
javascript复制// 假设当前URL是 https://www.example.com:8080/path/page.html?query=string#hash
console.log(window.location.href);
// 完整URL: "https://www.example.com:8080/path/page.html?query=string#hash"
console.log(window.location.origin);
// 协议+域名+端口: "https://www.example.com:8080"
console.log(window.location.pathname);
// 路径部分: "/path/page.html"
console.log(window.location.search);
// 查询参数: "?query=string"
console.log(window.location.hash);
// 哈希值: "#hash"
console.log(window.location.host);
// 域名+端口: "www.example.com:8080"
console.log(window.location.hostname);
// 纯域名: "www.example.com"
console.log(window.location.port);
// 端口: "8080"
console.log(window.location.protocol);
// 协议: "https:"
提示:在大多数现代浏览器中,直接使用
location而不加window.前缀也是可行的,因为window是全局对象。
2.2 使用document.location
document.location是另一种获取URL的方式,它与window.location基本等价:
javascript复制console.log(document.location.href === window.location.href); // true
不过在实际开发中更推荐使用window.location,因为:
- 语义更明确,表示获取的是窗口的地址
- 某些特殊环境下(如Web Worker)
document不可用而window可用
2.3 使用URL API(现代浏览器推荐)
ES6引入了URL API,提供了更强大的URL解析能力:
