history.replaceState() 與pushState() 的場(chǎng)景應(yīng)用區(qū)別

場(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
"
"
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);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容