首页 > 解决方案 > 获取在 onpopstate 事件中弹出的历史记录

问题描述

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

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

标签: javascripthtml5-history

解决方案


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

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

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


推荐阅读