1

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]
  }
})
David Alsh
  • 6,747
  • 6
  • 34
  • 60
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate – Jared Smith May 13 '21 at 00:24
  • Does this answer your question? [How to get notified about changes of the history via history.pushState?](https://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate) – Jared Smith May 13 '21 at 00:24
  • 1
    Almost, it answers that you can monkey patch history, not that it's reliable for monitoring SPA routing through all techniques (such as hash routing, and the specific details of react/vue/angular router). – David Alsh May 13 '21 at 00:27
  • You actually can't monkey patch history anymore anyway, assigning to it is a no-op now, at least in chrome and chromium-based browsers. – Jared Smith May 13 '21 at 00:28
  • Ah, but you can patch methods on it? – David Alsh May 13 '21 at 00:29
  • Yes, but your proxy idea won't work. – Jared Smith May 13 '21 at 01:16

0 Answers0