简体   繁体   English

Javascript pushState - 后退/前进按钮未按预期工作

[英]Javascript pushState - back / forward button not working as expected

I'm able to successfully push a url into the browser history using javascript window.history.pushState.我能够使用 javascript window.history.pushState 成功地将 url 推送到浏览器历史记录中。

I can click the browser's back and forward buttons and the urls change as expected.我可以单击浏览器的后退和前进按钮,网址会按预期更改。 However, it does not actually bring back the previous page's content.但是,它实际上并没有带回上一页的内容。

I can, manually, make this happen by clicking into the url bar and hitting the enter key, but I want to do this programmatically when the back or forward browser buttons are clicked.我可以通过单击 url 栏并按回车键来手动实现这一点,但我想在单击后退或前进浏览器按钮时以编程方式执行此操作。

I've already tried:我已经试过了:

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

and

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

My function to pushState:我的 pushState 函数:

var qstring = "?q=mysearchquery";

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

You will have to take care of rendering the content yourself using data pushed to history.您必须自己使用推送到历史记录的数据来渲染内容。

You should provide first argument to pushState function with data.您应该使用数据为pushState函数提供第一个参数。 This can be some page ID or plain HTML content.这可以是一些页面 ID 或纯 HTML 内容。 For example:例如:

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

or或者

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

Then in the event listener, you can get access to this data and use it to render your page, for example:然后在事件侦听器中,您可以访问此数据并使用它来呈现您的页面,例如:

$(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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM