javascriptdomgreasemonkeydom-events

Event when window.location.href changes


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.


Solution

  • 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'));
    };