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();
});
href = "https://www.example.com"; // Assigns a new URL to the current window. window. location. assign("https://www.example.com"); // Replaces the location of the current window with the new one.
The location. href property sets or returns the entire URL of the current page.
window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.
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.'; };
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"); });
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);
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