I'm developing a webpage where depending on the next or back actions I do the correspondent animation, the problem comes when using the pushstate. When I receive the event how do I know if the user clicked back or forward history buttons using the Pushstate API?, or do I have to implement something myself?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
You must implement it yourself which is quite easy.
pushState
give the data object a unique incrementing id (uid).onpopstate
handler is invoked; check the state uid against a persistent variable containing the last state uid.This answer should work with a single page push-state app, or a multi-page app, or a combination of the two. (Corrected to fix the
History.length
bug addressed in Mesqualito’s comment.)How it works
We can easily listen for new entries to the history stack. We know that for each new entry, the specification requires the browser to:
At the moment of entry, therefore:
The solution then is:
Example code
See also a live copy of the code.
Limitation
This solution ignores the history entries of external pages, foreign to the application, as though the user had never visited them. It calculates travel direction only in relation to the last shown application page, regardless of any external page visited in between. If you expect the user to push foreign entries onto the stack (see Atomosk’s comment), then you might need a workaround.