在前端开发中,经常会遇到获取当前网址的url、协议、域名、端口、路径、参数等情况,以下总结了几种常见的获取当前url的几种情形
获取url
window.location.href —— http://www.baidu.com:8080/test?id=123
获取协议
window.location.protocol —— http:
获取域名+端口
window.location.host —— www.baidu.com:8080
let host1 = window.location.host;
let host2 = document.domain;
let host3 = location.hostname;
获取域名
window.location.hostname —— www.baidu.com
获取端口
window.location.port —— 8080
获取路径
window.location.pathname —— /test
获取请求参数
window.location.search —— ?id=123
获取路径前面的url
window.location.origin —— www.baidu.com:8080
设置或获取 href 属性中在井号“#”后面的分段
window.location.hash
前进后退
window.history.forward()
window.history.back()
window.history.go(1)
//检测用户是通过前进还是后退访问页面
if (performance.navigation.type == performance.navigation.TYPE_BACK_FORWARD) {
console.log('用户通过后退访问页面');
} else {
console.log('用户通过其他方式访问页面');
}
//当前的有 10 条历史记录
console.log(window.history.length);
//history.state属性 history.replaceState(state, title, url)
window.history.pushState(null, '', '#aaa');
window.history.replaceState({a:1}, '', 'b.html')
window.history.state //{a:1}