Skip to content

New history event proposal #6

Closed
@frehner

Description

preface: this was first introduced here whatwg/html#5562 and at time of writing this message has a bit of positive "reaction" feedback (for a proposal, anyway 😄 ). Since this is a new place for proposals, I'm reopening the issue here. The original text is copy/pasted below, in hopes that 1) I'm doing this in the right spot, and 2) that it gains some traction. Please let me know if I've done something wrong - I'm open to feedback

Proposal

Add an event called statechange or historychange 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('historychange', (event) => {
  console.log('changed')
})

history.pushState(null, null, '/path')  // logs "changed"
location.hash = "sub" // logs "changed"

Side notes

This was created in collaboration with @joeldenning

Metadata

Assignees

No one assigned

    Labels

    Category: APIsGeneric category for proposals related to JS APIs (other than for JavaScript language enhancements)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions