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
pushStategive the data object a unique incrementing id (uid). - When
onpopstatehandler 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
Historyentry 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 ); }