Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement