HTML5标准之前
基本操作
1.forward(number) 加载histroy列表中的下一个URL
2.back(number) 加载histroy列表中的上一个URL
3.go(number) 根据当前所处的页面,加载 history 列表中的某个具体的页面。
例子:
前进(加载histroy列表中的下一个URL)
当下
后退(加载histroy列表中的上一个URL)
想去哪就去哪的go
function forward() {
//forward()相当于go(1)
window.history.forward();
}
function now() {
//forward()相当于go(0)
window.history.go(0);
}
function back() {
//forward()相当于go(-1)
window.history.back();
}
function go() {
window.history.go(10);
}
HTML5标准后
history.pushState()
新的状态信息就会被加入到history状态栈(列表),而浏览器地址栏也会变成新的相对URL。
var stateObj = { foo: "bar" };
window.history.pushState(stateObj, "page 2", "newly.html");
但是:浏览器不会刷新,这样也不会发送请求。
pushState 不会触发 onpopstate
这里需要与window.location.href='./newly.html'这个操作方法区分开。因为这个会刷新url,且发送请求。
history.replaceState()
更新当前历史记录条目的状态对象或URL。
var stateObj = { foo: "bar" };
window.history.replaceState(stateObj, "page 1", "app.html");
不同于window.location.replace(url)。浏览器不会刷新,这样也不会发送请求。
replaceState不会触发 onpopstate
图解:
onpopstate
onpopstate事件是用来监听URL发生变化的情况触发。
window.onpopstate = function(){
}