When changing pages on an SPA, frameworks interact with the history API or sometimes trigger hash changes to track routes.
Is there a reliable way to detect that an SPA, regardless of framework, has changed routes and perhaps trigger a CustomEvent
indicating that?
For example:
window.addEventListener('routechange', () => console.log('Navigation occurred'))
Would patching/proxying methods on the window.history
along with detecting url signatures on hash (includes /
?) on hashchange object suffice?
Something like:
const _history = window.history
window.history = new Proxy(_history, {
get(target, key) {
if (['pushState', 'replaceState', 'back', 'forward'].includes(key)) {
return () => {
window.dispatchEvent(new CustomEvent('routechange'))
return target[key]
}
}
return target[key]
}
})