preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.02k stars 155 forks source link

Feature request: property that indicates 'back' navigation #413

Open rejhgadellaa opened 2 years ago

rejhgadellaa commented 2 years ago

I'm working on a project where it would be really useful to know if the user navigated forward (push state) or backwards (pop state).

I had a look at the source code and it looks like the popstate event listener could call routeTo with an additional parameter that indicates the route is caused by the history popping a state.

Something like:

addEventListener('popstate', () => {
  routeTo(getCurrentUrl(), { isBack: true }); 
});

The parameter could then be stored in state and passed as a prop to the component and the onChangeRoute callback.

I did a little testing and got it working quite easily (see diffs here). I could make it a PR if this is something worth adding to preact-router.

Thanks!

developit commented 2 years ago

I think this would be a nice addition. The 'back' concept gets a bit murky when the user uses forward history navigation, since that also fires the popstate event. The new App History API provides an explicit indicator for this, but it's only available in Chrome currently.

TommyDew42 commented 2 years ago

Do we wanna use the new App History API to implement the new feature?

Happy to work on it!