概念
获取当前页面的地址信息,还可以修改某些属性,实现页面跳转和刷新等。
样例展示
window.location
含义.origin
URL 基础地址,包括协议名、域名和端口号.protocol
协议 (http:
或 https:
).host
域名+端口号.hostname
域名.port
端口号.pathname
路径(以/
开头).search
查询字符串,以?
开头.hash
页面锚点,以#
开头.href
完整 URL
比较容易混淆的是host
和hostname
这两个属性,区别是前者还包含了端口号。
修改属性值
以上属性除了origin
是只读属性,其他都可以修改。修改后的效果就是跳转到相应的新地址。
属性一览表
![](https://img-blog.csdnimg.cn/direct/44495c0391a44071a18562d6d048b448.png)
方法一览表
.assign()
导航到指定 URL.replace()
导航到指定 URL并删除当前页面的访问记录.reload()
重新加载当前页面.toString()
返回 URL 字符串
.toString()
和.href
都是返回 URL,它们之间有区别吗?结果是一样的,性能上稍微有点差别。通过 JSPerf 上的性能测试结果可以看出,.href
稍快,通过window.location
拼接字符串的形式速度最慢。
.assign()
和直接修改href
是等价的,那么它们跟.replace()
的区别是什么呢?
.assign()
在跳转新地址的同时会留下当前页面的访问记录,点击浏览器返回按钮会回到原来的页面,.replace()
则不会保留。
场景1:页面跳转锦集
location.href='https://www.baidu.com'
window.open('http://www.baidu.com','_self')
location.assign('http://www.baidu.com')
location.replace('http://www.baidu.com')
<a href="https://www.baidu.com">跳转</a>
- 页面中跳转固定的地址
function imitateClick(url){let aEle = document.createElement("a");aEle.setAttribute("href", url);aEle.setAttribute("target", "_blank");aEle.setAttribute("id", "previewJumpEle");// 防止重复添加if (!document.getElementById("previewJumpEle")) {document.body.appendChild(aEle);}// 模拟点击aEle.click();(aEle.remove && aEle.remove()) || (aEle.removeNode && aEle.removeNode(true));
};
imitateClick('https://www.baidu.com');
- js中直接做无感跳转,但是此方法有个弊端:经过验证,有的浏览器可能会拦截,慎用。
<meta http-equiv="refresh" content="5;url=http://www.w3school.com.cn">
场景2:检测协议并提示用户
if (location.protocol == 'http:') {this.$confirm('确定吗?').then(() => {location.href = 'https://www.baidu.com'})}