HTML页面的前进与后退,Javascript-如何检索popstate事件是来自HTML5 pushstate的后退动作还是前进动作?...

此答案应适用于单页面推送状态应用,或多页应用程序,或两者的组合。(已更正,以解决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的评论),那么您可能需要解决方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值