Detect an URL change in a SPA
Asked Answered
B

2

20

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

I found one solution here: https://mcmap.net/q/111097/-how-to-detect-url-changes-in-spa

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?

Bangle answered 14/11, 2018 at 15:24 Comment(1)
Does this answer your question? How to detect if URL has changed after hash in JavaScriptBacksaw
B
5

This https://mcmap.net/q/109106/-how-to-detect-if-url-has-changed-after-hash-in-javascript did the job for me, unbelievable we still have to use these hacks in 2018.

Bangle answered 14/11, 2018 at 18:34 Comment(0)
P
31

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);
Precentor answered 3/6, 2021 at 17:0 Comment(5)
From what I can tell this won't work? https://mcmap.net/q/112188/-how-to-use-or-is-it-possible-mutationobserver-to-monitor-window-location-pathname-changeAppenzell
@Appenzell it works, do you have more detail on what isn't working when you tried it?Precentor
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.Appenzell
You imitted mutationObserver.observe(target, options) - so your observer doesnt workCaudillo
This is a bad solution, observing deeply nested element leads to performance issues, and this one observing the entire document tree!Tableware
B
5

This https://mcmap.net/q/109106/-how-to-detect-if-url-has-changed-after-hash-in-javascript did the job for me, unbelievable we still have to use these hacks in 2018.

Bangle answered 14/11, 2018 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.