'onchange event on window.location.href
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();
});
Solution 1:[1]
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.';
};
Solution 2:[2]
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");
});
Solution 3:[3]
There's no built-in event that gets triggered on all url changes. let's see why:
window.addEventListener('hashchange',listener)
- triggers only when there's a change in hash (#) in URL.
window.addEventListener('popstate', listener);
- triggers only when the user clicks the back button and not on
pushState()orreplaceState()event. Useless for SPA sites.
window.onbeforeunload()
- won't work for SPA sites and on hashchange.
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeroen |
| Solution 2 | mt025 |
| Solution 3 | GorvGoyl |
