我有一个 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')
在您的案例中使用历史对象之前,您应该覆盖它。因此,您将可以访问历史状态的副本。 它也可能在历史中也可以访问,但我不知道你是否可以访问它。
关于javascript - 获取 onpopstate 事件弹出的历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665333/