当前窗口的浏览历史 window.history 对象html
保存了当前窗口访问过的全部页面网址
跨域
因为安全缘由,浏览器不容许脚本读取这些地址,可是容许在地址之间导航浏览器
history.back() 至关于 history.go(-1)缓存
浏览器工具栏的 “前进” 和 “后退” 按钮,其实就是对 History 对象进行操做安全
// 当前窗口访问过多少个网页 window.history.length // 1 // History 对象的当前状态 // 一般是 undefined,即未设置 window.history.state // undefined
主要有两个属性
服务器
5 个方法函数
history.back() ---- 移动到上一个网址,等同于点击浏览器的后退键工具
对于第一个访问的网址,该方法无效果网站
history.forward() ---- 移动到下一个网址,等同于点击浏览器的前进键google
对于最后一个访问的网址,该方法无效果
history.go() ---- 接受一个整数做为参数,以当前网址为基准,移动到参数指定的网址
好比 go(1) 至关于forward() go(-1)至关于back()
若是参数超过实际存在的网址范围,该方法无效果
若是不指定参数,默认参数为 0,至关于刷新当前页面
注意: 移动到之前访问过的页面时,页面一般是从浏览器缓存之中加载,而不是从新要求服务器发送新的网页
history.pushState() ---- 用于在历史中添加一条记录
window.history.pushState(state, title, url)
不会触发页面刷新,只是致使 history 对象发生变化,地址栏会有反应
使用该方法以后,就能够用 history.state
属性读出状态对象
var stateObj = { foo: 'bar' }; history.pushState(stateObj, 'page 2', '2.html'); history.state // {foo: "bar"}
pushState
的 URL 参数设置了一个新的锚点值(即 hash
),并不会触发 hashchange
事件pushState()
方法设置了一个跨域网址,则会报错这样设计的目的是,防止恶意代码让用户觉得他们是在另外一个网站上
由于这个方法不会致使页面跳转
接受三个参数
state ---- 一个与添加的记录相关联的状态对象,主要用于 popstate 事件
该事件触发时,该对象会传入回调函数
也就是说,浏览器会将这个对象序列化之后保留在本地
从新载入这个页面的时候,能够拿到这个对象。
若是不须要这个对象,此处能够填 null
title ---- 新页面的标题
如今全部浏览器都忽视这个参数,因此这里能够填空字符串
url ---- 新的网址
必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址
假定当前网址是 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
你再点击一次倒退按钮,URL 将显示 1.html
history.replaceState() ---- 用来修改 History 对象的当前记录,其余都与 pushState() 方法如出一辙
假定当前网页是 example.com/example.html
history.pushState({page: 1}, 'title 1', '?page=1') // URL 显示为 http://example.com/example.html?page=1 history.pushState({page: 2}, 'title 2', '?page=2'); // URL 显示为 http://example.com/example.html?page=2 history.replaceState({page: 3}, 'title 3', '?page=3'); // URL 显示为 http://example.com/example.html?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
popstate 事件
每当同一个文档的浏览历史(即 history 对象)出现变化时,就会触发 popstate 事件
仅仅调用 pushState() 方法或 replaceState() 方法 ,并不会触发该事件
该事件只针对同一个文档,若是浏览历史的切换,致使加载不一样的文档,该事件也不会触发
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
对象也能够直接经过 history
对象读取
var currentState = history.state;
注意,页面第一次加载的时候,浏览器不会触发popstate事件