我必须维护一个带有AJAX搜索表单的网站(比如书籍),我希望搜索结果成为浏览器历史记录的一部分 .
所以我设置了 "popstate" 事件处理程序
window.addEventListener('popstate', function(e) {
alert("popstate: " + JSON.stringify(e.state));
});
并在成功的AJAX请求时调用 pushState() :
var stateObj = { q: "harry potter" };
window.history.pushState(stateObj, "Result", "/search");
然后我的点击流是:
-
使用搜索表单加载页面 - NORMAL请求 - 路径为/
-
输入查询字符串并提交表单 - AJAX请求 - 路径更改为/ search
-
点击搜索结果 - 正常请求 - 路径更改为/ books / harry-potter
- When I now go back by clicking the browser back button I would expect the "popstate" event to be triggered with the according state object. But nothing happens. - 路径更改为/ search
-
当我再回去一次时,我收到
popstate: null
的警报 - 路径更改为/ -
当我继续前进之后,我得到
popstate: {"q":"harry potter"}
- 路径更改为/ search
So, the important popstate event (the one with the query string) gets only triggered when going forward, but not when going back.
这是因为我从一个站点导航回来,其历史记录条目是自动创建的,而不是由pushState以编程方式创建的?但如果是这样,历史API只对完整的单页面应用程序有意义 .
任何浏览器中的行为都是相同的 . 希望你能帮助我:)
1 回答
对于想要更多解释为什么popstate事件仅在某些情况下发生的人,这有助于我:
在MDN popstate event page它说:
和
因此,只有在导航到同一文档中的不同URL时才会调用popstate . 这适用于SPA,但不适用于其他任何事情 .
作为补充说明,html5 spec for session history似乎没有太多关于何时调用popstate事件的清晰度:
这可能表明不同的浏览器会以不同的方式对待它 .
我希望得到更多来自其他人的见解