location对象
location对象包含了有关当前URL的相关信息(它是window对象的一个属性):
window.location.href === location.href
属性
1、 location.hash 返回是从#开始的URL,如果地址没有#,返回时空字符串。
http://localhost:8080/#/sec?name=lxc
location.hash // #/sec?name=lxc
2、 location.host 返回是主机名和当前URL端口号。
http://localhost:8080/#/sec
location.host // localhost:8080
3、 location.hostname 返回是主机名
http://localhost:8080/#/sec
location.hostname // localhost
4、 location.href 返回、设置完整的URL路径(包含查询参数)
http://localhost:8080/#/sec?name=lxc
location.href // http://localhost:8080/#/sec?name=lxc
5、 location.protocol 返回、设置URL的协议 ( 后边的带冒号: )
http://localhost:8080/#/sec?name=lxc
location.protocol // http:
6、 location.origin 返回页面的域名(只读)
http://localhost:8080/sec
location.origin // http://localhost:8080
7、 location.pathname 返回第一个 /后边的路径, 包含 /
http://localhost:8080/sec?name=lxc
location.pathname // /sec
8、 location.search 返回 问号后边的查询参数(包含问号)
http://localhost:8080/sec?name=lxc
location.search // ?name=lxc
方法
1、location.reload( )
重新加载来自当前URL的资源。它有一个特殊的可选参数,类型为Boolean,该参数为true时,会导致该方法引发刷新一定会从服务器上加载数据。如果是false或没有指定这个参数,浏览器可能从缓存当中加载页面。
2、location.replace( )
用给定的URL替换掉当前的资源,用replace()替换的新页面,不会被保存在会话的历史History中,这意味着用户将不能用后退按钮转到该页面。
MDN上的一个例子:
'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';
console.log(location.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(location.protocol); // https:
console.log(location.host); // developer.mozilla.org
console.log(location.hostname); // developer.mozilla.org
console.log(location.port); // (blank - https assumes port 443)
console.log(location.pathname); // /en-US/search
console.log(location.search); // ?q=URL
console.log(location.hash); // #search-results-close-container
console.log(location.origin); // https://developer.mozilla.org