window.location 备忘单

2025-05-26

window.location 备忘单

替代文本

想要查找网站的 URL 信息,这个window.location对象正适合你!使用它的属性获取当前页面地址的信息,或者使用它的方法进行页面重定向或刷新 💫

https://www.samanthaming.com/tidbits/?filter=JS#2

window.location.origin    'https://www.samanthaming.com'
               .protocol  'https:'
               .host      'www.samanthaming.com'
               .hostname  'www.samanthaming.com'
               .port      ''
               .pathname  '/tidbits/'
               .search    '?filter=JS'
               .hash      '#2'
               .href      'https://www.samanthaming.com/tidbits/?filter=JS#2'
Enter fullscreen mode Exit fullscreen mode
window.location.assign('url')
               .replace('url')
               .reload()
               .toString()
Enter fullscreen mode Exit fullscreen mode

window.location 属性

window.location 返回
.origin 基本 URL(协议 + 主机名 + 端口号)
.protocol 协议模式(http:或https
.host 域名+端口
.hostname 域名
.port 端口号
.pathname 初始“/”后跟路径
.search ?后跟查询字符串
.hash #后跟锚点或片段标识符
.href 完整网址

host和之间的区别hostname

在我上面的例子中,你会注意到hosthostname返回值。那么为什么需要这些属性呢?嗯,这与端口号有关。我们来看一下。

不带端口的 URL

https://www.samanthaming.com

window.location.host; // 'www.samanthaming.com'
window.location.hostname; // 'www.samanthaming.com'

window.location.port; // ''
Enter fullscreen mode Exit fullscreen mode

带端口的 URL

https://www.samanthaming.com:8080

window.location.host; // 'www.samanthaming.com:8080'
window.location.hostname; // 'www.samanthaming.com'

window.location.port; // '8080'
Enter fullscreen mode Exit fullscreen mode

因此host将包括端口号,而hostname仅返回主机名。

如何更改 URL 属性

您不仅可以调用这些位置属性来检索 URL 信息,还可以使用它来设置新属性并更改 URL。让我们看看我的意思。

// START 'www.samanthaming.com'

window.location.pathname = '/tidbits'; // Set the pathname

// RESULT 'www.samanthaming.com/tidbits'
Enter fullscreen mode Exit fullscreen mode

以下是您可以更改的属性的完整列表:

// Example
window.location.protocol = 'https'
               .host     = 'localhost:8080'
               .hostname = 'localhost'
               .port     = '8080'
               .pathname = 'path'
               .search   = 'query string' // (you don't need to pass ?)
               .hash     = 'hash' // (you don't need to pass #)
               .href     = 'url'
Enter fullscreen mode Exit fullscreen mode

唯一无法设置的属性是window.location.origin。此属性是只读的。

位置对象

返回window.location一个Location对象,其中包含页面当前位置的信息。您也可以Location通过多种方式访问​​该对象。

window.location           Location
window.document.location  Location
document.location         Location
location                  Location
Enter fullscreen mode Exit fullscreen mode

我们之所以能够这样做是因为这些是浏览器中的全局变量。

替代文本

window.location 与 location

这四个属性都指向同一个Location对象。我个人更喜欢window.location使用 ,实际上我会避免使用location。主要是因为location它读起来更像是一个通用术语,而且有人可能会不小心给自己的变量起一个覆盖全局变量的名字。例如:

// https://www.samanthaming.com

location.protocol; // 'https'

function localFile() {
  const location = '/sam';

  return location.protocol;
  // ❌ undefined
  //    b/c local "location" has override the global variable
}
Enter fullscreen mode Exit fullscreen mode

我想大多数开发者都知道这window是一个全局变量。这样就不容易造成混淆了。说实话,location在写这篇文章之前我根本不知道这是一个全局变量😅。所以我的建议是更明确地使用window.location👍

以下是我个人的偏好顺序:

// ✅
1. window.location   // 🏆
2. document.location

// ❌
3. window.document.location //  why not just use #1 or #2 😅
4. location // feels too ambiguous 😵
Enter fullscreen mode Exit fullscreen mode

当然,这只是我的个人偏好。你是你代码库的专家,没有最好的方法,最好的方法永远是最适合你和你的团队的方法🤓

window.location 方法

window.location
.assign() 导航到给定的 URL
.replace() 导航到给定的 URL 并从会话历史记录中删除当前页面
.reload() 重新加载当前页面
.toString() 返回 URL

窗口.位置.toString

这是来自MDN的定义

此方法返回URL 的USVString。它是 Location.href 的只读版本。

换句话说,你可以使用它href

// https://www.samanthaming.com

window.location.href; // https://www.samanthaming.com
window.location.toString(); // https://www.samanthaming.com
Enter fullscreen mode Exit fullscreen mode

至于该用哪个,我找不到太多信息来说明哪个更好;不过如果你找到了,请提交一个 PR 😊。不过我确实找到了一个关于两者差异的性能测试。

JSPerf:Location toString 与 Location href

关于这些速度测试,我想指出的一点是,它与浏览器相关。不同的浏览器和版本会呈现不同的结果。我用的是 Chrome,所以href比其他浏览器更快。所以我会用它。而且我觉得它读起来比 更清晰toString()。 很明显href会提供 URL,而toString看起来像是被转换成字符串了 😅

分配与替换

这两种方法都可以帮助您重定向或导航到另一个 URL。区别在于,它们会将当前页面assign保存在历史记录中,以便用户可以使用“返回”按钮导航到该页面。而使用方法则不会保存历史记录。感到困惑吗?没关系,我也是。我们来看一个例子。replace

分配

1. Open a new blank page
2. Go to www.samanthaming.com (current page)

3. Load new page 👉 `window.location.assign('https://www.w3schools.com')`
4. Press "Back"
5. Returns to 👉 www.samanthaming.com
Enter fullscreen mode Exit fullscreen mode

代替

1. Open a new blank place
2. Go to www.samanthaming.com (current Page)

3. Load new page 👉 `window.location.replace('https://www.w3schools.com')`
4. Press "Back"
5. Return to 👉 blank page
Enter fullscreen mode Exit fullscreen mode

当前页面

我只需要强调定义中的“当前页面”。它是调用assign或之前的页面replace

1. Open a new blank place
2. Go to www.developer.mozilla.org
3. Go to www.samanthaming.com 👈 this is the current Page
Enter fullscreen mode Exit fullscreen mode
4. window.location.assign('https://www.w3schools.com'); // Will go to #3
4. window.location.replace('https://www.w3schools.com'); // Will go to #2
Enter fullscreen mode Exit fullscreen mode

如何进行页面重定向

window.location现在,您知道我们可以通过使用 赋值来更改 的属性=。同样,我们也可以访问一些方法来执行某些操作。因此,关于“如何重定向到另一个页面”,有三种方法。

// Setting href properties
window.location.href = 'https://www.samanthaming.com';

// Using Assign
window.location.assign('https://www.samanthaming.com');

// Using Replace
window.location.replace('https://www.samanthaming.com');
Enter fullscreen mode Exit fullscreen mode

替换 vs 赋值 vs href

这三种方法都会重定向,区别在于浏览器历史记录。hrefassign在这方面是一样的。它会将当前页面保存在历史记录中,而 则replace不会。所以,如果你希望打造一种导航无法按回原始页面的体验,那么请使用replace👍

所以现在的问题是hrefvs assign。我想这取决于个人喜好。我assign更喜欢 ,因为它是一个方法,所以感觉就像我在执行某个操作。此外,它还有一个额外的好处,那就是更容易测试。我写过很多 Jest 测试,所以使用方法更容易模拟。

window.location.assign = jest.fn();

myUrlUpdateFunction();

expect(window.location.assign).toBeCalledWith('http://my.url');
Enter fullscreen mode Exit fullscreen mode

来源StackOverflow:@kieranroneill

但对于这一点,我支持href进行页面重定向。我找到了一个性能测试,在我的 Chrome 版本上运行,速度更快。同样,性能测试会因浏览器和版本而异,现在速度可能更快,但也许在未来的浏览器中,速度会有所调整。

JSPerf:href 与分配

挠你自己的痒处👍

好吧,稍微扯点题外话,先简单介绍一下这份速查表的由来。我在谷歌搜索如何重定向到另一个页面时,遇到了 window.location 对象。有时候我觉得开发者就像记者或侦探——需要挖掘和梳理多个来源才能收集到所有可用的信息。说实话,我被外面的资料淹没了,它们涵盖了不同的内容,但我只想要一个来源。我找不到太多资料,所以我想,就用一份小贴士速查表来介绍一下!我总是说,自己摸索着解决自己的问题吧👍

资源

感谢阅读❤
打个招呼!Instagram | Twitter | SamanthaMing.com

文章来源:https://dev.to/samanthaming/window-location-cheatsheet-4edl
PREV
C# 项目创意 100+ 项目创意 教程 创意
NEXT
JavaScript 模块速查表