Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect an URL change in a SPA

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?

like image 695
wasddd_ Avatar asked Nov 14 '18 15:11

wasddd_


People also ask

Does URL change in Spa?

Most SPAs load website resources on the first page load. Thereafter, the URLs of the website do not change.

How to detect browser URL change?

To Detect URL Change in JavaScript Without Refresh we use MutationObserver() function. And JavaScript location.

How to detect if URL has changed JavaScript?

You can use the popstate method to detect those URL changes and make UI changes as needed. window. addEventListener('popstate', function (event) { // The URL changed... }); Yesterday, we learned that the first property passed into the history.


1 Answers

Now that most browser's 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);
like image 165
d-_-b Avatar answered Oct 11 '22 01:10

d-_-b