JavaScript Window Location

Location 对象是"地址栏的化身":它把当前页面的完整 URL 拆成协议、域名、端口、路径、查询参数、锚点等一个个零件,还提供跳转和刷新方法。做"登录后跳回原页面""分享链接带参数""阅读进度锚点"等功能都靠它。它在 window 上,直接写 location 即可。以下示例在浏览器控制台运行。

Location 对象能拿到什么

location 对象(也叫 window.location)本身就是当前页面的 URL 字符串,也带着 URL 的详细属性:

console.log(location.href);        // 输出:https://example.com/page/js-window-location.html
console.log(location === window.location);  // 输出:true
console.log(location.hostname);    // 输出:example.com,域名
console.log(location.pathname);    // 输出:/js/js-window-location.html,路径
console.log(location.protocol);    // 输出:https:,协议
console.log(location.port);        // 输出:(空),没写端口时为空字符串

location.href 与 window.location 在地址栏内容变化时自动保持同步,这就是"单点真源"。

URL 的各个零件

拿一个带查询参数和锚点的网址演示:https://example.com/search?q=js&page=2#top

// 假设当前网址为 https://example.com/search?q=js&page=2#top
console.log(location.href);       // 输出:https://example.com/search?q=js&page=2#top
console.log(location.protocol);   // 输出:https:
console.log(location.host);       // 输出:example.com(含端口)
console.log(location.pathname);   // 输出:/search
console.log(location.search);     // 输出:?q=js&page=2,查询参数
console.log(location.hash);       // 输出:#top,锚点
console.log(location.origin);     // 输出:https://example.com,协议+域名+端口

search 和 hash 都以 ? 和 # 开头,做"分享带参链接"时经常要拼这两个值。

跳转:href 赋值与 assign

给 location.href 赋值就会跳转,等价于 location.assign(url),两者都会在历史里留下记录:

location.href = "https://example.com";   // 效果:页面立即跳转到 example.com 首页
location.assign("https://example.com");  // 同上,功能完全等价
// 想让用户点按钮再跳,就把上面任一行放进按钮的 onclick 回调里

href 赋值与 assign 都会在浏览器历史中新增一条记录,用户按"后退"能返回当前页。

replace 与 reload

replace 跳转但不在历史里留当前页;reload 刷新当前页面:

location.replace("https://example.com/js/js-intro.html");
// 效果:跳到 JS 教程页,且本页不进历史,后退键回不到本页
location.reload();   // 效果:重新加载当前页面(等价于按 F5)

登录成功跳到首页时常用 replace,避免用户按后退"绕回"登录页再操作一次。

实战:从查询参数读值

location.search 拿到的是 "?a=1&b=2" 这样的原文,写个小函数解析成对象:

function getParams() {
  let params = {};
  let str = location.search.replace(/^\?/, "");  // 去掉开头的 ?
  if (!str) return params;
  str.split("&").forEach(function (item) {
    let pair = item.split("=");
    params[pair[0]] = decodeURIComponent(pair[1] || "");
  });
  return params;
}
// 假设网址是 https://example.com/?from=news&uid=88
console.log(getParams());   // 输出:{ from: 'news', uid: '88' }

decodeURIComponent 负责把 %E4%B8%AD 之类的编码还原成中文字符,别忘了加。

小结:location 就是地址栏,href 是整个网址、hostname/pathname/search/hash/origin 等属性拆出 URL 各部分;跳转用 href 赋值或 assign,不留历史用 replace,刷新用 reload;需要读取 URL 参数时把 search 用 & 和 = 拆开解析即可。

笔记加载中…