javascript - 获取在 onpopstate 事件中弹出的历史记录
问题描述
我有一个事件的听众onpopstate
。我想获得没有在历史中旅行而弹出的历史记录。我可以做到history.forward()
并获得状态,但这会导致我不想看到的副作用。
window.addEventListener('popstate', (event) => {
prevHistoryRecord = // How to get it without history.forward()
});
解决方案
我假设您想要访问由框架或应用程序的其他部分添加/修改的状态。在这种情况下,您可以覆盖历史函数并监听,将状态更改存储在您可以访问的对象中
const historyState = []
const fn = history.pushState.bind(history)
history.pushState = function() {
console.log('Push state', arguments)
historyState.push({ args: arguments })
fn.apply(history, arguments)
}
history.pushState('arg1', 'arg2')
在您的案例中使用它之前,您应该覆盖历史对象。因此,您将可以访问历史状态的副本。它也可能在历史中也可以访问,但我不知道您是否可以访问它。
推荐阅读
- c# - why is my call to CountCharsAsync blocking the UI?
- c++ - 尝试使用对 protobuffers 2.6.1 和 3.4.1 的引用来编译代码
- redis - Redis 立即保存到磁盘,即使配置为不
- android - 如何修复设计Android?
- python - 每次迭代存储不同变量的循环?
- apache - SSL 库错误(键值不匹配),但证书文件确实匹配
- r - 将数值批量转换为因子
- javascript - Gulp 中的 ES6 模块
- java - 将 jar 运行到苹果脚本中
- ruby-on-rails - 在哪里放置 ruby 助手 Sendgrid V3 发送 API