使用 JavaScript 获取当前 URL
技术背景
在前端开发中,有时需要获取当前页面的 URL 信息,例如在进行页面跳转、数据请求、页面分析等操作时。JavaScript 提供了多种方法来获取当前 URL 及其各个组成部分。
实现步骤
1. 获取完整的当前 URL
可以使用 window.location.href
或 document.URL
来获取完整的当前 URL。
1 2 3 4 5 6 7
| const fullUrl1 = window.location.href; console.log(fullUrl1);
const fullUrl2 = document.URL; console.log(fullUrl2);
|
2. 获取 URL 的各个组成部分
JavaScript 的 Location
对象提供了多个属性来获取 URL 的各个部分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const currentLocation = window.location;
const protocol = currentLocation.protocol;
const host = currentLocation.host;
const hostname = currentLocation.hostname;
const port = currentLocation.port;
const pathname = currentLocation.pathname;
const search = currentLocation.search;
const hash = currentLocation.hash;
const origin = currentLocation.origin;
console.log('协议:', protocol); console.log('主机名和端口:', host); console.log('主机名:', hostname); console.log('端口号:', port); console.log('路径名:', pathname); console.log('查询字符串:', search); console.log('锚点:', hash); console.log('源:', origin);
|
3. 使用 URL
对象解析 URL
URL
对象可以方便地解析和操作 URL。
1 2 3 4 5 6 7 8
| const url = new URL(window.location.href);
const name = url.searchParams.get('name'); const age = url.searchParams.get('age');
console.log('name 参数:', name); console.log('age 参数:', age);
|
核心代码
获取完整 URL
1
| const fullUrl = window.location.href;
|
获取 URL 各部分
1 2 3 4 5 6 7 8 9
| const currentLocation = window.location; const protocol = currentLocation.protocol; const host = currentLocation.host; const hostname = currentLocation.hostname; const port = currentLocation.port; const pathname = currentLocation.pathname; const search = currentLocation.search; const hash = currentLocation.hash; const origin = currentLocation.origin;
|
使用 URL
对象解析查询参数
1 2
| const url = new URL(window.location.href); const paramValue = url.searchParams.get('paramName');
|
最佳实践
- 优先使用
window.location.href
:虽然 document.URL
也能获取完整 URL,但在某些特殊情况下(如存在名为 URL
的框架、图像或表单)可能会出现问题,因此建议优先使用 window.location.href
。 - 使用
URL
对象处理查询参数:当需要处理 URL 中的查询参数时,使用 URL
对象的 searchParams
属性可以更方便地获取和操作参数。
常见问题
1. document.URL
和 window.location.href
有什么区别?
一般情况下,它们返回的值是相同的。但在某些特殊情况下,如存在名为 URL
的框架、图像或表单时,document.URL
可能会被覆盖,导致代码出错,而 window.location.href
则不会受此影响。
2. window.location
和 document.location
有什么关系?
在现代浏览器中,document.location
会被映射到 window.location
。但最初 document.location
只返回当前 URL 字符串,为避免混淆,后来引入了 document.URL
。为了跨浏览器兼容性,建议使用 window.location
。
3. 如何判断 URL 中是否包含某个查询参数?
可以使用 URL
对象的 searchParams.has()
方法来判断。
1 2 3
| const url = new URL(window.location.href); const hasParam = url.searchParams.has('paramName'); console.log('是否包含 paramName 参数:', hasParam);
|