I have a single page app with pagination and filters, and need to detect when the current URL changes at all. Is there not a simple way to add a listener to the current URL and trigger something when it changes? (No setting intervals either!)
I have tried both onhashchange, and tried unbeforeunload, and neither are relevant for this.
window.onbeforeunload = function(e) {
alert ('url changed!');
};
window.onhashchange = function() {
alert ('url changed!');
}
Is there a way to add a listener to the URL, and trigger something anytime it changes at all? (again, single page app so no refresh)
If you don't want to use setInterval, you can override the history.pushState
event:
(function(history){
const pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({state: state});
}
// Call your custom function here
return pushState.apply(history, arguments);
}
})(window.history);
you can use MutationObserver to listen to URL changes amongst other things:
let previousUrl = '';
const observer = new MutationObserver(function(mutations) {
if (window.location.href !== previousUrl) {
previousUrl = window.location.href;
console.log(`URL changed from ${previousUrl} to ${window.location.href}`);
}
});
const config = {subtree: true, childList: true};
// start listening to changes
observer.observe(document, config);
// stop listening to changes
// observer.disconnect();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With