[英]Javascript pushState - back / forward button not working as expected
我能够使用 javascript window.history.pushState 成功地将 url 推送到浏览器历史记录中。
我可以单击浏览器的后退和前进按钮,网址会按预期更改。 但是,它实际上并没有带回上一页的内容。
我可以通过单击 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);
}
}
您必须自己使用推送到历史记录的数据来渲染内容。
您应该使用数据为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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.