How do I retrieve if the popstate event comes from back or forward actions with the HTML5 pushstate?
Check the history.state
object for a source
property to discern whether the popstate event signifies a back or forward action. Remember to assign 'back' or 'forward' as the source property when utilizing history.pushState
.
Example:
As can be seen, we manually track the navigation direction, which is just us taking the situation into our own reliable hands!
Supplementing with UID tracker
To further enrich our direction tracking capabilities, we can introduce a unique incrementing ID (UID). This notable addition into the state object maintains a historical record of navigation alterations, which, in turn, gifts us the ability to accurately deduce the navigation direction.
Add unique incrementing IDs to state
Each push state harbors a UID that ascends in value:
Using 'onpopstate' to discern direction
By appropriating the onpopstate event handler, we can ascertain direction:
It's important to note, while most history entries will cooperate with our neat tracking system, those originating from external pages may play a less amiable game.
Sharp moves with Math.sign
Use powerhouse Math.sign for sharper direction deduction:
Pinpoint position using Math.sign
Check out this upgrade. We are dealing with position values now:
Keep in mind, history entries from external pages may require a unique handle, and deep historical navigation can have its fun intricacies!
Marking history for clarity
Use timestamps or unique identifiers to mark each history entry, making the navigation crystal clear:
Example of history stamping
Add a timestamp to state for precision:
Handling stamped data
In each popstate event, compare timestamps to make the direction of navigation as clear as a sunny day.
Was this article helpful?