Event when window.location.href changes

Johan Dahlin picture Johan Dahlin · Aug 19, 2010 · Viewed 177k times · Source

I'm writing a Greasemonkey script for a site which at some point modifies location.href.

How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page? I also need access to the DOM of the document pointing to the new/modified url.

I've seen other solutions which involve timeouts and polling, but I'd like to avoid that if possible.

Answer

PHF picture PHF · Nov 12, 2015

popstate event:

The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)

So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:

window.addEventListener('popstate', listener);

const pushUrl = (href) => {
  history.pushState({}, '', href);
  window.dispatchEvent(new Event('popstate'));
};