美文网首页JavaScript
history.replaceState() 与pushStat

history.replaceState() 与pushStat

作者: 凝黛色 | 来源:发表于2019-03-05 13:56 被阅读0次

    场景需求:

    如下图所示,用户可以在previousPage通过点击事件到达showcolor页面,showcolor页面有3个子页面,分别是red,green,yellow 页面,为了记录用户的点击行为,在用户进入子页面的时候在url上加上hash值加以区分。当用户点击浏览器的返回按钮时,可以正确的返回到前一页面,而不是在子页面之间层层返回。


    demo.png

    实现方式:

    • 使用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
    

    这三种方式在展现hash方面的结果是一致的,但是对于浏览器的返回按钮被点击时的反应不同。

    • 使用history.replaceState() 的方式
      基于replaceState() 是修改了当前的历史记录项而不是新建一个,所以无论用户在showcolor页面多少次的点开不同的子颜色页面,当点击返回时,都会回到https://test.bigtest.com/previousPage页面。
    "
    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】初始化进入color页面时
      初始化color页面时,需要做一次replaceState()函数的操作,为了防止用户在https://test.bigtest.com/showcolor#Red 直接刷新,那么因为#Red的hash值不会自动清除,所以不会自动返回到https://test.bigtest.com/showcolor页面,如果想要刷新后自动定位到showcolor页面,那么在 showcolor页面初始化的时候需要做一次replaceState()函数的操作。
    init(){
     window.history.replaceState("", document.title, window.location.pathname);
    }
    

    相关文章

      网友评论

        本文标题:history.replaceState() 与pushStat

        本文链接:https://www.haomeiwen.com/subject/peqwuqtx.html