history 与 hashchange 原生 api

window.onpopstate = console.log
window.onhashchange = console.log
1. history.pushState({a:1,b:2}, 'title', '/test')   // /test
2. history.pushState({test:2,b:33}, 'title2', '/test2') // /test2
3. 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与hashchange
9. history.back()     // 触发history与hashchange

总结

  1. replaceState与pushState 相似,会替换替换url, 不会增加history长度
  2. 不在history最顶层的时pushState 会将此url 上层的记录替换为 pushSate的那条记录。
  3. hashchange 事件触发条件为,非pushState和replaceState 引起的hash变化
  4. onhashchange 事件触发条件为, 非pushState和replaceState 引起的 url变化。
  5. locaiton.href 操作只改hash 会触发2个事件。但是如果改了url 则会重新加载,不管是否有history记录。
  6. 刷新页面history依然保存
  7. location.href 在页面加载时自动跳转去其他页面时,不会记录history,但如果手动点击按钮跳转,不管是否是异步,都会记录history.
原文地址:https://www.cnblogs.com/gsgs/p/12989831.html