Get history record which was popped on onpopstate event

Viewed 891

I have a listener to onpopstate event. I want to get record of history which was popped without travelling in history. I could do history.forward() and get state, but that will cause side-effects I don't want to see.

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

I assume you want to access a state added/modified by a framework or other part of your application. In that case, you can overwrite history functions and listen, store state changes in an object, which is accessible to you

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

You should overwrite history object before it has been used in your case. So, you will have access to a copy of history state. It might also be accessible in History as well but I have no idea if you can reach it.

Related