浏览器窗口有一个history对象,用来保存浏览历史。javascript
若是当前窗口前后访问了三个网址,那么history对象就包括三项,history.length属性等于3。html
history对象提供了一系列方法,容许在浏览历史之间移动:java
window.history.back():移动到上一个访问页面,等同于浏览器的后退键。浏览器
window.history.forward():移动到下一个访问页面,等同于浏览器的前进键。缓存
window.history.go(num):接受一个整数做为参数,移动到该整数指定的页面,好比go(1)至关于forward(),go(-1)至关于back()。服务器
window.history.pushState():HTML5为history对象添加了两个新方法,window.history.pushState()和window.history.replaceState(),用来在浏览历史中添加和修改记录。函数
注:1.若是移动的位置超出了访问历史的边界,以上三个方法并不报错,而是默默的失败。url
2.设置时,页面一般是从浏览器缓存之中加载,而不是从新要求服务器发送新的网页。spa
重点讲解下:window.history.pushState().net
window.history.pushState(state, title, utl),在页面中建立一个 history 实体。直接添加到历史记录中。
其中参数:
state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数。若是不须要这个对象,此处能够填null。
title:新页面的标题,可是全部浏览器目前都忽略这个值,所以这里能够填null。
url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。
注:pushState方法不会触发页面刷新,只是致使history对象发生变化,地址栏会有反应。
举例实现:
Html5 监听拦截Android返回键方法以下:
1.监听 popstate 事件
window.addEventListener("popstate", function(){ //doSomething }, false)
2.取消默认的返回操做,即监听拦截返回键:添加一条空的 history 实体做为替代原来的 history 实体
window.history.pushState(null, null, "#");
举例:
<!DOCTYPE html> <html> <meta name="viewport" content="width=device-width"> <script type="text/javascript"> var count = 0 ; window.history.pushState(null, null, "#"); window.addEventListener("popstate", function(e) { window.history.pushState(null, null, "#"); document.getElementById('logView').innerHTML = "用户点击返回" + (++count) }) </script> <body> <p id="logView">test</p> </body> </html>
参考:https://my.oschina.net/xtdhwl/blog/1068692