javascript - Javascript pushState - 后退/前进按钮未按预期工作
问题描述
我能够使用 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);
});
推荐阅读
- shell - 如何编写批处理脚本来运行多个 adb shell 命令
- html - 如何使用 flexbox CSS 将两个项目连续隔开?
- angular - isStable 在角度中的真正含义是什么?
- python-3.x - 当我在 python 中使用 wptools 时导入错误
- python - 运行此程序时,我不断收到“BrokenPipeError: [Errno 32] Broken pipe”,但我不知道为什么
- avd - 带有华为移动服务和不带谷歌移动服务的 AVD
- python - 如何使我的 FacetGrid 绘图适用于以下数据?
- r - 在 rshiny 中的 mathjax 中的单词之间添加一个空格
- arrays - 无法理解使用 malloc 创建二维数组
- c - 如果再次执行,函数中的文件指针增量会保持该增量吗?