如果需要获取网站的 URL 信息,那么window.location对象就是为你准备的。window.location返回一个Location对象。它提供有关页面当前 URL 的信息。
以一个常见的 URL 为例:www.samanthaming.com/tidbits/?fi…
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'
window.location 属性
通过它不但可以获取当前页面的地址信息,还可以修改某些属性,实现页面跳转和刷新等。以下是可以更改的属性的完整列表:
// Example
window.location.protocol = 'https'
.host = 'localhost:8080'
.hostname = 'localhost'
.port = '8080'
.pathname = 'path'
.search = 'query string' // (不需要传入 ?)
.hash = 'hash' // (不需要传入 #)
.href = 'url'
唯一不能设置的属性是 window.location.origin 。
window.location 函数
window.location.assign('url')
.replace('url')
.reload()
.toString()