浏览器监听返回键

546 阅读1分钟

需要监听用户点击返回键定制一些操作

前置条件:在一个页面

例如:通过点击一个按钮执行pushHistory();修改url 在这个页面点击返回键就可以捕获到

<button onclick="pushHistory();" style="width: 200px;height: 200px;">点击我,去下一个页面吧...

window.addEventListener("popstate", function (e) {

      alert("捕获成功");

    });

    function pushHistory() {

      //添加一个hash

      var state = {

        title: "title",

        url: "#forward"

      };

      window.history.pushState(state, null, "#forward");

      alert('新页面?')

    }