12

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,438
  • 68
  • 55
  • 126
wasddd_
  • 648
  • 1
  • 9
  • 17
  • 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

14

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,182
  • 5
  • 42
  • 47
d-_-b
  • 19,976
  • 37
  • 134
  • 224
  • 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
5

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

wasddd_
  • 648
  • 1
  • 9
  • 17