Event for detecting URL changes via History API


#1

The History API currently provides a popstate event for detecting navigations via browser controls in a single-page application but I’m not aware of a clean way to listen for changes to the URL as a result of uses of history.{pushState|replaceState}.

My use case is for reacting to URL changes in a 3rd-party widget embedded in a page which displays content related to the current URL, specifically the Hypothesis tool for annotating web pages. Some additional use cases described at http://stackoverflow.com/q/4570093/434243 include browser extensions. In both cases the top-level document may not be aware of the 3rd-pary widget so it has not been architected to push changes to it (eg. via an attribute on the widget or calling some function on a controller provided by the widget).

Perhaps this could take the form of a locationchange event which is fired whenever the URL changes for any reason or a pushstate event which is triggered only when history.replaceState or history.pushState are used. Thoughts?


#2

Perhaps this could take the form of a locationchange event which is fired whenever the URL changes for any reason or a pushstate event which is triggered only when history.replaceState or history.pushState are used. Thoughts?

I think what you want is a StateChanged event which behaves similar to PopState event but for all backward, forward, an in-place modifications of the history state stack. This can be useful when you want to observer URL changes but also in a more general case of observing any page state modifications. It may even be better to have a state mutation observer instead of an event.

As pointed out in the linked stack overflow discussion, this may be achieved by monkey-patching the history object. I am not sure if this is possible on all browsers and for it to work the monkey patching should occur before the page has a chance to hold a private reference to the history object.

My use case is for reacting to URL changes in a 3rd-party widget embedded in a page which displays content related to the current URL, specifically the Hypothesis tool for annotating web pages. Some additional use cases described at http://stackoverflow.com/q/4570093/4342431 include browser extensions.

FWIW, this is anecdotal but some popular routing libraries provide a similar hook (e.g., ReactRouter has onUpdate) which also indicate that there is some need for it.