Reputation: 2105
I would like to trigger some Javascript function when window.location.href
link changes. Is it possible?
Something like this:
$(window.location.href).on('change', function(){
doSomething();
});
Upvotes: 24
Views: 55508
Reputation: 49180
There's no built-in event that gets triggered on all url changes. let's see why:
window.addEventListener('hashchange',listener)
window.addEventListener('popstate', listener);
pushState()
or replaceState()
event. Useless for SPA sites.window.onbeforeunload()
So, is there a way?
Yes, using MutationObserver:
let previousUrl = "";
const observer = new MutationObserver(() => {
if (window.location.href !== previousUrl) {
console.log(`URL changed from ${previousUrl} to ${window.location.href}`);
previousUrl = window.location.href;
// do your thing
}
});
const config = { subtree: true, childList: true };
// start observing change
observer.observe(document, config);
Upvotes: 12
Reputation: 5672
You said 'something like', given the example code you're probably looking for the onbeforeunload
event handler.
From the Mozilla docs:
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
Upvotes: 43
Reputation: 371
The hashchange event occurs when there has been changes to the URL anchor part i.e after the #
window.addEventListener('hashchange', function() {
alert("Hash Changed");
});
Upvotes: 15