【问题标题】:Get history record which was popped on onpopstate event获取在 onpopstate 事件中弹出的历史记录
【发布时间】:2019-11-02 01:20:06
【问题描述】:

我有一个onpopstate 事件的侦听器。我想获得没有在历史中旅行而弹出的历史记录。我可以做history.forward() 并获取状态,但这会导致我不想看到的副作用。

window.addEventListener('popstate', (event) => {
    prevHistoryRecord = // How to get it without history.forward()
});

【问题讨论】:

  • 为什么不简单地使用 event.state 或 history.state?
  • 因为事件状态和历史状态存储的是当前状态,而不是被弹出的状态

标签: javascript html5-history


【解决方案1】:

我假设您想要访问由框架或应用程序的其他部分添加/修改的状态。在这种情况下,您可以覆盖历史函数并监听,将状态更改存储在您可以访问的对象中

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')

您应该在历史对象用于您的案例之前覆盖它。因此,您将可以访问历史状态的副本。 它也可能在历史中也可以访问,但我不知道您是否可以访问它。

【讨论】:

  • 我不喜欢修改全局对象及其方法的想法,因为它会降低隔离度并在未来导致不可预测的行为(例如,有人决定在我导入的其他 repo 中修改 pushState,他不会知道他会破坏我的应用程序,我将无法找到问题所在)
  • 好吧,api 没有给出状态对象。我认为您无法通过其他方式访问它。这是一个安全的副作用,但我同意这不是最漂亮的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
相关资源
最近更新 更多