1. 程式人生 > 實用技巧 >history 與 hashchange 原生 api

history 與 hashchange 原生 api

非重新整理頁面跳轉(history跳轉或者location.hash 跳轉)

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 (location.hash) 操作只改hash 會觸發2個事件。但是如果改了url 則會重新載入,不管是否有history記錄。
  6. 重新整理頁面history依然儲存

重新整理頁面跳轉(location.href改變路徑)

location.href的跳轉(不含location.hash="#xxx"),屬於重新整理頁面跳轉,不管是history.back() 還是返回按鈕,都會重新整理頁面,不會觸發任何事件(hashchange,popstate)。
如果記錄了history,則可以使用history.back(),但不一定能使用自帶返回按鈕,返回上一頁,如下:

自動跳轉 例如:a→b→c
  1. 點選返回按鈕,c→a 頁。
  2. 在頁面載入時自動跳轉到其他頁面,如果在window.onload之前或者onload中的同步程式碼進行跳轉, history不記錄,如果在onload時機後的下一個事件佇列進行跳轉,則記錄hisotry(上條規則仍然存在)。
手動跳轉

記錄history 點選返回按鈕 跳到前一頁