大部分來自mdn上原文,可是mdn上順序敘述不清晰,本身從新整理了一下本身的閱讀筆記
window 對象經過 history 對象提供了對瀏覽器的回話歷史的訪問。它暴露了不少有用的方法和屬性,容許你在用戶瀏覽歷史中向前和向後跳轉。從HTML5
開始——提供了對history棧中內容的操做。html
能夠讀取當前歷史記錄項的狀態對象state
,而沒必要等待popstate
事件, 只須要使用history.state
屬性瀏覽器
這裏引伸出了popstate事件,因此插入討論一下popstate
:this
當活動歷史記錄條目更改時,將觸發popstate事件。若是被激活的歷史記錄條目是經過對history.pushState()的調用建立的,或者受到對history.replaceState()的調用的影響,popstate事件的state屬性(event.state)包含歷史條目的狀態對象的副本。code
須要注意的是調用 history.pushState()
或history.replaceState()
不會觸發popstate事件。只有在作出瀏覽器動做時,纔會觸發該事件,如用戶點擊瀏覽器的回退按鈕(或者在Javascript代碼中調用history.back())htm
window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2);
使用 back()
, forward()
和 go()
方法來完成在用戶歷史記錄中向後和向前的跳轉。對象
能夠經過查看長度屬性的值來肯定的歷史堆棧中頁面的數量:事件
window.history.length
HTML5引入了 history.pushState()
和 history.replaceState()
方法,它們分別能夠添加和修改歷史記錄條目。這些方法一般與window.onpopstate
配合使用。ip
使用 history.pushState() 能夠改變referrer(報文頭,用來指明當前流量的來源參考頁),它在用戶發送 XMLHttpRequest 請求時在HTTP頭部使用,改變state後建立的 XMLHttpRequest 對象的referrer都會被改變。由於referrer是標識建立 XMLHttpRequest 對象時 this 所表明的window對象中document的URL。string