此答案应适用于单页面推送状态应用,或多页应用程序,或两者的组合。(已更正,以解决Mesqualito的注释中提到的History.length错误。)
这个怎么运作
我们可以轻松地侦听历史记录堆栈中的新条目。我们知道,对于每个新条目,该规范都要求浏览器:
“在当前条目之后删除浏览上下文的会话历史记录中的所有条目”
“最后添加一个新条目”
因此,在入境时:
新输入位置=最后显示的位置+ 1
然后的解决方案是:
在堆栈中以自己的位置标记每个历史记录条目
在会话存储中跟踪最后显示的位置
通过比较两者来发现行进方向
范例程式码
function reorient() // After travelling in the history stack
{
const positionLastShown = Number( // If none, then zero
sessionStorage.getItem( 'positionLastShown' ));
let position = history.state; // Absolute position in stack
if( position === null ) // Meaning a new entry on the stack
{
position = positionLastShown + 1; // Top of stack
// (1) Stamp the entry with its own position in the stack
history.replaceState( position, /*no title*/'' );
}
// (2) Keep track of the last position shown
sessionStorage.setItem( 'positionLastShown', String(position) );
// (3) Discover the direction of travel by comparing the two
const direction = Math.sign( position - positionLastShown );
console.log( 'Travel direction is ' + direction );
// One of backward (-1), reload (0) or forward (1)
}
addEventListener( 'pageshow', reorient );
addEventListener( 'popstate', reorient ); // Travel in same page
另请参见代码的实时副本。
局限性
此解决方案将忽略外部页面的历史记录条目,对应用程序而言是陌生的,就好像用户从未访问过它们一样。它仅针对最后显示的应用页面计算行驶方向,不论其间访问过任何外部页面。如果您希望用户将外部条目推入堆栈(请参阅Atomosk的评论),那么您可能需要解决方法。