【问题标题】:Javascript pushState - back / forward button not working as expectedJavascript pushState - 后退/前进按钮未按预期工作
【发布时间】:2019-12-09 10:44:33
【问题描述】:

我能够使用 javascript window.history.pushState 成功地将 url 推送到浏览器历史记录中。

我可以单击浏览器的后退和前进按钮,并且网址会按预期更改。但是,它实际上并没有带回上一页的内容。

我可以通过点击网址栏并按回车键手动实现这一点,但我想在点击后退或前进浏览器按钮时以编程方式执行此操作。

我已经试过了:

$(window).on("popstate", function() {
  alert("Back/Forward button was pressed.");
  window.location.reload(); // <-- brings back the page, but ruins the browser history stack. 
});

$(window).on("popstate", function() {
  alert("Back/Forward button was pressed.");
  window.location.href = window.location.href;
});

我的 pushState 函数:

var qstring = "?q=mysearchquery";

function addURLToHistoryAPI(qstring) {
  if (window.history && window.history.pushState) {
    window.history.pushState(null, null, qstring);
  }
}

【问题讨论】:

    标签: javascript pushstate


    【解决方案1】:

    您必须自己使用推送到历史记录的数据来渲染内容。

    您应该为pushState 函数提供第一个参数和数据。这可以是一些页面 ID 或纯 HTML 内容。例如:

    window.history.pushState(currentPageID, null, qstring);
    

    window.history.pushState($("main").html(), null, qstring);
    

    然后在事件监听器中,您可以访问这些数据并使用它来呈现您的页面,例如:

    $(window).on("popstate", e => {
        alert("Back/Forward button was pressed.");
    
        // "e.originalEvent.state" contains the data passed in the first argument
        console.log(e.originalEvent.state);
        $("main").html(e.originalEvent.state);
    });
    

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 2017-09-01
      • 1970-01-01
      • 2020-04-10
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多