目录javascript
1 history对象概述html
1.1 属性说明 java
1.2 方法说明浏览器
2 history.pushState(),history.replaceState()函数
4 popstate事件google
浏览器窗口有一个history对象,用来保存浏览历史。好比,该窗口前后访问了三个地址,那么history对象就包括三项,length属性等于3。url
history.length // 3
属性 | 说明 |
length | 历史列表的长度,用于判断列表中的入口数目 |
current | 当前文档URL |
next | 历史列表的下一个URL |
previous | 历史列表的前一个URL |
方法 | 说明 |
back() | 返回前一页 |
forward() | 从新进入下一页 |
go() | 进入指定的网页 |
history对象提供了一系列方法,容许在浏览历史之间移动。spa
history.back(); history.forward(); history.go(-2);
若是移动的位置超出了访问历史的边界,以上三个方法并不报错,而是默默的失败。设计
如下命令至关于刷新当前页面。
history.go(0);
HTML5为history对象添加了两个新方法,history.pushState() 和 history.replaceState(),用来在浏览历史中添加和修改记录。全部主流浏览器都支持该方法(包括IE10)。
if (!!(window.history && history.pushState)){ // 支持History API } else { // 不支持 }
上面代码能够用来检查,当前浏览器是否支持History API。若是不支持的话,能够考虑使用Polyfill库history.js。
history.pushState方法接受三个参数,依次为:
假定当前网址是example.com/1.html
,咱们使用pushState方法在浏览记录(history对象)中添加一个新记录。
var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2", "2.html");
添加上面这个新记录后,浏览器地址栏马上显示example.com/2.html
,但并不会跳转到2.html,甚至也不会检查2.html是否存在,它只是成为浏览历史中的最新记录。假定这时你访问了google.com,而后点击了倒退按钮,页面的url将显示2.html,可是内容仍是原来的1.html。你再点击一次倒退按钮,url将显示1.html,内容不变。
注意,pushState方法不会触发页面刷新。
若是 pushState 的url参数,设置了一个当前网页的#号值(即hash),并不会触发hashchange事件。若是设置了一个非同域的网址,则会报错。
// 报错 history.pushState(null, null, 'https://twitter.com/hello');
上面代码中,pushState想要插入一个非同域的网址,致使报错。这样设计的目的是,防止恶意代码让用户觉得他们是在另外一个网站上。
history.replaceState方法的参数与pushState方法如出一辙,区别是它修改浏览历史中当前页面的值。假定当前网页是example.com/example.html。
history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // url显示为http://example.com/example.html?page=1 history.back(); // url显示为http://example.com/example.html history.go(2); // url显示为http://example.com/example.html?page=3
history.state属性保存当前页面的state对象。
history.pushState({page: 1}, "title 1", "?page=1"); history.state // { page: 1 }
每当同一个文档的浏览历史(即history对象)出现变化时,就会触发popstate事件。须要注意的是,仅仅调用pushState方法或replaceState方法 ,并不会触发该事件,只有用户点击浏览器倒退按钮和前进按钮,或者使用JavaScript调用back、forward、go方法时才会触发。另外,该事件只针对同一个文档,若是浏览历史的切换,致使加载不一样的文档,该事件也不会触发。
使用的时候,能够为popstate事件指定回调函数。这个回调函数的参数是一个event事件对象,它的state属性指向pushState和replaceState方法为当前url所提供的状态对象(即这两个方法的第一个参数)。
window.onpopstate = function(event) { console.log("location: " + document.location); console.log("state: " + JSON.stringify(event.state)); }; // 或者 window.addEventListener('popstate', function(event) { console.log("location: " + document.location); console.log("state: " + JSON.stringify(event.state)); });
上面代码中的event.state,就是经过pushState和replaceState方法,为当前url绑定的state对象。
这个state对象也能够直接经过history对象读取。
var currentState = history.state;
另外,须要注意的是,当页面第一次加载的时候,在onload事件发生后,Chrome和Safari浏览器(Webkit核心)会触发popstate事件,而Firefox和IE浏览器不会。