以下是 window.location 所有属性的详细解释,结合具体场景和示例说明,帮助直观理解每个属性的作用:
1. href
作用:获取或设置当前页面的完整 URL(字符串形式)。
示例场景:
用户点击按钮跳转到新页面。
动态跟踪当前页面 URL。
代码示例:
// 当前URL: https://example.com/shop?item=shoes#reviews console.log(window.location.href); // 输出: "https://example.com/shop?item=shoes#reviews" // 跳转到新页面 window.location.href = "https://example.com/contact";
2. protocol
作用:返回 URL 的协议(包含冒号
:)。示例场景:
检查当前页面是否使用 HTTPS。
代码示例:
// URL: https://example.com
console.log(window.location.protocol); // 输出: "https:"
// 强制切换到 HTTPS
if (window.location.protocol === "http:") {
window.location.protocol = "https:";
}3. hostname
作用:返回 URL 的域名(不含端口)。
示例场景:
根据域名显示不同的页面内容。
代码示例:
// URL: https://example.com:8080
console.log(window.location.hostname); // 输出: "example.com"
// 判断是否为测试环境
if (window.location.hostname === "test.example.com") {
showDebugTools();
}4. port
作用:返回 URL 的端口号(未指定时返回空字符串)。
示例场景:
检测开发环境端口。
代码示例:
// URL: http://localhost:3000
console.log(window.location.port); // 输出: "3000"
// 默认端口处理
if (!window.location.port) {
console.log("使用默认端口(80/443)");
}5. pathname
作用:返回 URL 的路径部分(以
/开头)。示例场景:
高亮当前导航菜单项。
代码示例:
// URL: https://example.com/products/phones
console.log(window.location.pathname); // 输出: "/products/phones"
// 动态生成面包屑导航
const paths = window.location.pathname.split('/').filter(Boolean);
// paths = ["products", "phones"]6. search
作用:返回 URL 的查询参数部分(以
?开头)。示例场景:
解析商品筛选参数。
代码示例:
// URL: https://example.com?category=electronics&sort=price
console.log(window.location.search); // 输出: "?category=electronics&sort=price"
// 转换为对象
const params = new URLSearchParams(window.location.search);
console.log(params.get("category")); // 输出: "electronics"7. hash
作用:返回 URL 的锚点部分(以
#开头)。示例场景:
实现单页面应用(SPA)的路由。
代码示例:
// URL: https://example.com#settings
console.log(window.location.hash); // 输出: "#settings"
// 监听锚点变化
window.addEventListener("hashchange", () => {
console.log("当前锚点:", window.location.hash);
});8. host
作用:返回域名和端口(若端口存在)。
示例场景:
显示完整的服务地址。
代码示例:
// URL: https://example.com:8080 console.log(window.location.host); // 输出: "example.com:8080"
9. origin
作用:返回协议 + 域名 + 端口(只读)。
示例场景:
构建 API 请求的基础 URL。
代码示例:
// URL: https://example.com:8080
console.log(window.location.origin); // 输出: "https://example.com:8080"
// 动态请求同源API
fetch(`${window.location.origin}/api/data`);对比总结
通过实际案例结合属性操作,可以更灵活地控制浏览器地址和页面行为。