Skip to content

Instantly share code, notes, and snippets.

@frehner
Last active May 15, 2020 19:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frehner/e4684d8b312d3623ea4ab3b9ef1da2c7 to your computer and use it in GitHub Desktop.
Save frehner/e4684d8b312d3623ea4ab3b9ef1da2c7 to your computer and use it in GitHub Desktop.
This is a work-in-progress proposal

Proposal

Add an event called statechange that will fire on any change to the history stack, whether that be through the browser's back button, or window.history.pushState or other methods.

This proposed event would be similar to popstate, except that it would fire on all route changes regardless of the source, much like hashchange fires on all hash changes regardless of the source.

Current Problems

hashchange events allowed javascript router libraries (e.g. React Router, vue-router) to easily respond to any routing event when the application is using hash routing.

However, with the HTML5 History API, there is no equivalent event that javascript routers can listen to.

This means that routers have the following limitations/problems:

  • They assume that they're the only Router that exists on the page - Routers require all code to call into it whenever making a URL change
  • Users cannot call window.history.pushState directly and must only use the Router's custom methods
  • Third party libraries that may want to change the URL or cause a Router to update have a difficult time since they can't call native APIs

References:

remix-run/react-router#6304

Example

window.addEventListener('statechange', (event) => {
  // url changed!
})
@blittle
Copy link

blittle commented May 15, 2020

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment