場(chǎng)景需求:
如下圖所示,用戶可以在previousPage通過(guò)點(diǎn)擊事件到達(dá)showcolor頁(yè)面,showcolor頁(yè)面有3個(gè)子頁(yè)面,分別是red,green,yellow 頁(yè)面,為了記錄用戶的點(diǎn)擊行為,在用戶進(jìn)入子頁(yè)面的時(shí)候在url上加上hash值加以區(qū)分。當(dāng)用戶點(diǎn)擊瀏覽器的返回按鈕時(shí),可以正確的返回到前一頁(yè)面,而不是在子頁(yè)面之間層層返回。

demo.png
實(shí)現(xiàn)方式:
- 使用history.replaceState() 的方式
window.history.replaceState("", document.title, '#Red');
#url : https://test.bigtest.com/showcolor#Red
- 使用history.pushState() 的方式
window.history.pushState("", document.title, '#Red');
#url : https://test.bigtest.com/showcolor#Red
- 使用window.location.hash的方式
window.location.hash ="#Red"
#url : https://test.bigtest.com/showcolor#Red
這三種方式在展現(xiàn)hash方面的結(jié)果是一致的,但是對(duì)于瀏覽器的返回按鈕被點(diǎn)擊時(shí)的反應(yīng)不同。
- 使用history.replaceState() 的方式
基于replaceState() 是修改了當(dāng)前的歷史記錄項(xiàng)而不是新建一個(gè),所以無(wú)論用戶在showcolor頁(yè)面多少次的點(diǎn)開不同的子顏色頁(yè)面,當(dāng)點(diǎn)擊返回時(shí),都會(huì)回到https://test.bigtest.com/previousPage頁(yè)面。
"
https://test.bigtest.com/showcolor#Red OR https://test.bigtest.com/showcolor---->https://test.bigtest.com/previousPage
"
- 使用history.pushState() 的方式或window.location.hash的方式
pushState()是新建了History對(duì)象的記錄,所以黨在子頁(yè)面https://test.bigtest.com/showcolor#Red點(diǎn)擊返回按鈕時(shí),會(huì)先返回到https://test.bigtest.com/showcolor頁(yè)面,然后再次點(diǎn)擊返回按鈕才會(huì)返回到https://test.bigtest.com/previousPage
"
https://test.bigtest.com/showcolor#Red ---->https://test.bigtest.com/showcolor---->https://test.bigtest.com/previousPage
"
- 【tip】初始化進(jìn)入color頁(yè)面時(shí)
初始化color頁(yè)面時(shí),需要做一次replaceState()函數(shù)的操作,為了防止用戶在https://test.bigtest.com/showcolor#Red 直接刷新,那么因?yàn)?Red的hash值不會(huì)自動(dòng)清除,所以不會(huì)自動(dòng)返回到https://test.bigtest.com/showcolor頁(yè)面,如果想要刷新后自動(dòng)定位到showcolor頁(yè)面,那么在 showcolor頁(yè)面初始化的時(shí)候需要做一次replaceState()函數(shù)的操作。
init(){
window.history.replaceState("", document.title, window.location.pathname);
}