Search code examples
javascripthtmlbrowser-historypushstate

How do I retrieve if the popstate event comes from back or forward actions with the HTML5 pushstate?


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?


Solution

  • You must implement it yourself which is quite easy.

    • When invoking pushState give the data object a unique incrementing id (uid).
    • When onpopstate handler is invoked; check the state uid against a persistent variable containing the last state uid.
    • Update the persistent variable with the current state uid.
    • Do different actions depending on if state uid was greater or less than last state uid.