HTML5 history.pushState()和history.replaceState()新增、修改历史记录用法介绍

1、使用pushState()方法 可以控制浏览器自带的返回按钮:

有时候我们想让用户点击浏览器返回按钮时,不返回,或执行其他操作,这时,就用到history.pushState()方法

讲解:

history.pushState(data,title,url) //每执行一次都会增加一条历史记录,浏览器在返回时,就不会返回前一个页面了,

data:要设置的history.state的值,可以是任意类型的值,可根据此值进行判断执行想要的操作。

   title:现在大多数浏览器不支持或者忽略这个参数,最好用null代替。

     url:地址栏的值,若不需要可用空来代替。

// 监听浏览器的前进后退事件:

     window.addEventListener("popstate", function() {
        // 取出 设置好的 history.state 值,做判断

     });
示例:

 
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <button class="btn" onclick="btnFun();">点击新增一条历史记录</button>
    </div>
    <script>
        console.log('增加历史记录前 state的值:',history.state); // null  function btnFun() {//点击事件  // 增加一个历史记录  history.pushState('a',null,'2.html?b=1');
            console.log('增加历史记录后 state的值:',history.state); // a  };
        window.addEventListener('popstate',function() {
            var state = history.state;//取出state //注意:在此处时(点击后退按钮时),state的值已经为null  // (因为返回时历史记录会被删除,浏览器动作)  console.log('点击后退按钮后 state的值:',state); // null  //判断,想要执行的操作   });
    </script>
</body>
</html>



2、history.replaceState() 与pushState()功能类似,除了这点:

replaceState()是用来修改当前的历史记录(history实体),而不是创建一个新的历史记录,所以,当执行完history.replaceState()后,点击返回按钮照样会返回上一个一面。  当需要更新一个state对象或者当前history实体时,可以用replaceState()来实现。

用法:当在a页面使用replaceState()修改了历史记录后,跳转到b页面,后退到a页面时,历史记录就是修改过的。

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <button class="btn" onclick="btnFun();">点击修改本页历史记录</button>
    </div>
    <br/>
    <div>
        <a href="b.html">点击跳转到b页面</a>
    </div>
    <script>

        function btnFun() {//点击事件  history.replaceState('a',null,'a.html?a=1');
            console.log('修改历史记录后 state的值:',history.state); // a  };
    </script>
</body>
</html>


点击跳转到b页面后 ,执行返回操作


回到a页面,url中?a=1还存在,我们可以利用这个参数在页面中执行一些操作,比如列表的选中