20

I would like to listen to path changes in a SPA which is not maintained by me.

I found one solution here: https://stackoverflow.com/a/44819548/7042552

But still, it seems kind of "hacky" to me - but still my implementation is like this:

let url = window.location.href;

['click','popstate', 'onload'].forEach( evt =>
        window.addEventListener(evt, function () {
            requestAnimationFrame(()=>{
                if (url !== location.href) {
                    // do stuff
                }
                url = location.href;
            });
        }, true)
    );

Is there a better or more generic way to listen for page loads in a SPA?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
wasddd_
  • 937
  • 2
  • 10
  • 19
  • Does this answer your question? [How to detect if URL has changed after hash in JavaScript](https://stackoverflow.com/questions/6390341/how-to-detect-if-url-has-changed-after-hash-in-javascript) – Brian Tompsett - 汤莱恩 Dec 13 '20 at 00:00

2 Answers2

25

Now that most browsers support MutationObserver, you can use code like this to detect URL changes in a SPA:

let previousUrl = '';
const observer = new MutationObserver(function(mutations) {
  if (location.href !== previousUrl) {
      previousUrl = location.href;
      console.log(`URL changed to ${location.href}`);
    }
});
const config = {subtree: true, childList: true};
observer.observe(document, config);
Ehtesh Choudhury
  • 7,452
  • 5
  • 42
  • 48
d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • From what I can tell this won't work? https://stackoverflow.com/a/32158577/1540547 – jorgen Oct 05 '21 at 09:50
  • @jorgen it works, do you have more detail on what isn't working when you tried it? – d-_-b Oct 05 '21 at 15:34
  • Hello! When I tried it just didn't trigger on URL change. I didn't go deeply into it though, as I thought it wouldn't work after reading the above link, so I might be wrong. – jorgen Oct 07 '21 at 05:16
  • You imitted `mutationObserver.observe(target, options)` - so your observer doesnt work – avalanche1 Dec 06 '21 at 20:18
  • This is a bad solution, observing deeply nested element leads to performance issues, and this one observing the entire document tree! – Caleb Taylor Dec 15 '22 at 01:28
5

This https://stackoverflow.com/a/41825103/7042552 did the job for me, unbelievable we still have to use these hacks in 2018.

wasddd_
  • 937
  • 2
  • 10
  • 19