简体   繁体   中英

Get history record which was popped on onpopstate event

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()
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM