Puchacz
Puchacz

Reputation: 2105

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();
});

Upvotes: 24

Views: 55508

Answers (3)

GorvGoyl
GorvGoyl

Reputation: 49180

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() or replaceState() 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);

Upvotes: 12

elzi
elzi

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

ashwin1014
ashwin1014

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

Related Questions