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

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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?

回答1:

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.


回答2:

Here’s a generalized answer. This approach should work with single-page, push-state apps; but also with traditional multi-page apps, or combinations of the two.

How it works

  • Stamp each History entry with its own position in the stack
  • Stamp the session with the last position shown
  • Discover the direction of travel by comparing the two

Example code

     reorient(); // on page load     addEventListener( 'pageshow', ( /*PageTransitionEvent*/show ) =>     {         if( show.persisted ) reorient();         // else page is newly loaded and already *reorient* was called above     });     addEventListener( 'popstate', reorient );       /** Reorient after a position change in the history stack.       */     function reorient()     {         let state = history.state;         let direction; /* (-1, 0, 1) = (backward, reload, forward)           position of this entry vs. last entry (of ours) that was shown */         if( state === null ) // then this entry is new to the stack         {             const position = history.length - 1; // top of stack             direction = 1;            // Stamp the entry with its own position in the stack           // ---------------             state = String( position );             history.replaceState( state, /*no title*/'' );         }         else // this entry was pre-existing         {             const position = Number( state );             const stateLastShown = sessionStorage.getItem( 'stateLastShown' );             console.assert( stateLastShown,               'All our entries persist state in History' );             const positionLastShown = Number( stateLastShown );             direction = Math.sign( position - positionLastShown );         }        // Answer the question       // -------------------         console.log( 'travel direction was ' + direction );        // Stamp the session with the last position shown       // -----------------         sessionStorage.setItem( 'stateLastShown', state );     }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!