window.onpopstate = console.logwindow.onhashchange = console.log1. history.pushState({a:1,b:2}, ‘title‘, ‘/test‘) // /test2. history.pushState({test:2,b:33}, ‘title2‘, ‘/test2‘) // /test23. history.back() // /test log: {state:{a:1,b:2},...other}4. history.forward() // /test2 log: {state:{test:2,b:33}, ...other}5. history.back()6. history.pushState({test: 3, b:44}, ‘title3‘, ‘/test3‘) // history.length === 2 /test2被删除7. location.hash = ‘#test3‘ // 会立刻触发onpopstate与hashchange 并且增加history记录。8. history.pushState(null,‘‘,‘#a‘) // 不会触发history与hashchange9. history.back() // 触发history与hashchange
总结
- replaceState与pushState 相似,会替换替换url, 不会增加history长度
- 不在history最顶层的时pushState 会将此url 上层的记录替换为 pushSate的那条记录。
- 刷新页面,当前url 置为 history最顶层(删除此url以后的记录),此url以下的记录不变。
- hashchange 事件触发条件为,非pushState和replaceState 引起的hash变化
- onhashchange 事件触发条件为, 非pushState和replaceState 引起的 url变化。
- locaiton.href 操作只改hash 会触发2个事件。但是如果改了url 则会重新加载,不管是否有history记录。