23

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();
});
Jeroen
  • 60,696
  • 40
  • 206
  • 339
Puchacz
  • 1,987
  • 2
  • 24
  • 38
  • The change event only fires on some input elements (textarea, select, input) – Brennan Nov 06 '14 at 21:08
  • 7
    I suspect he's asking this because he's changing the url on the fly. I found this question for a similar reason. – Axle Jan 16 '15 at 18:14

3 Answers3

43

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.';
};
Jeroen
  • 60,696
  • 40
  • 206
  • 339
elzi
  • 5,442
  • 7
  • 37
  • 61
  • 4
    notice this won't detect some location events such as [hashchange](http://stackoverflow.com/questions/680785/on-window-location-hash-change) or [history manipulation](http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page). – cregox May 14 '17 at 01:41
15

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");

});
mt025
  • 273
  • 4
  • 13
ashwin1014
  • 351
  • 1
  • 5
  • 18
  • This is a code-only answer. Code-only answers may be valid, but get automatically flagged as low quality. Please add a short explanation why this code works, or what the error was. -[From review](https://stackoverflow.com/review/low-quality-posts/17604650) – Erik A Oct 12 '17 at 10:09
9

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);
GorvGoyl
  • 42,508
  • 29
  • 229
  • 225