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.
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:
window.addEventListener('statechange', (event) => {
// url changed!
})
👍