想获取站点的URL信息,那么window.location
对象比较适合。使用其属性获取有关当前页面地址的信息,使用其方法进行某些页面重定向或刷新。
https://segmentfault.com/search?q=前端#1
window.location.origin = 'https://segmentfault.com';
.protocol = 'https:'
.host = 'segmentfault.com'
.hostname = 'segmentfault.com'
.port = ''
.pathname = '/search'
.search = '?q=前端'
.hash = '#1'
.href = 'https://segmentfault.com/search?q=前端#1'
window.location.assign('url')
.replace('url')
.reload()
.toString()
window.location属性
window.location | 返回值 |
---|---|
.origin | 站点主地址(协议 + 主机名 + 端口) |
.protocol | 协议架构(http: 或者 https) |
.host | 域名 + 端口 |
.port | 端口 |
.pathname | 最前面的’/后面跟的路径’ |
.search | ? 后面跟的路径 |
.hash | 从#号开始的部分 |
.href | 完整网址 |
host 与 hostname 的区别
主要与端口号有关
没有端口的url
https://segmentfault.com/search
window.location.host // segmentfault.com
window.location.hostname // segmentfault.com
window.location.port // ''
带端口的url
https://segmentfault.com:8080/search
window.location.host // segmentfault.com:8080
window.location.hostname // segmentfault.com
window.location.port // 8080
如何更改URL属性
我们不仅可以使用 location
属性来检索URL信息,还可以使用它来设置并更新URL。
// 开始 https://segmentfault.com
window.location.pathname = 'topics'
// 结果 https://segmentfault.com/topics
下面是你可以更新的所有属性列表
// 事例
window.location.protocol = 'https'
.host = 'localhost:8080'
.hostname = 'localhost'
.port = '8080'
.pathname = 'path'
.search = 'query string' // (这里不用写 `?`)
.hash = 'hash' // (这里不用写 `#`)
.href = 'url'
唯一不能设置的属性是window.location.origin
属性,此属性是只读的
Location 对象
window.location
返回一个Location
对象,它为我们提供有关当前页面地址的信息,但是我们还可以通过几种方式访问Location
对象。
window.location --> Location
window.document.location --> Location
document.location --> Location
location --> Location
window.location vs location
上面四个属性都指向同一个Location
对象。但是应该避免使用location
对象。主要因为location
对象看起来像一个普通变量,并且有时我们可能会不小心将其命名为变量,这将覆盖全局变量。举个例子:
// https://segmentfault.com
location.protocol; // https
function localFile() {
const location = '/aaa'
return location.protocol; // undefined
}
window.location 方法
方法 | 作用 |
---|---|
.assign | 加载一个新的文档 |
.replace() | 用新的文档替换之前的文档 |
.reload() | 重新加载当前文档 |
assign vs replace
这两种方法都是重定向或导航到另一个URL。区别在于assign
是将当前的页面保存到历史记录中,因此用户可以使用“后退”按钮导航到该页面。而使用replace
方法时,不会保存它。
如何让页面重定向
如何重定向到另一个页面,有3种方法
window.location.href = 'https://www.csdn.net'
window.location.assign('https://www.csdn.net')
window.location.replace('https://www.csdn.net')