Html5监听返回事件

常使用的场景:移动前端
1、安卓手机物理返回键
2、苹果手机在企业微信打开浏览器的返回按钮

移动前端开发语言是:vue
路由跳转:vue-router hash模式

先介绍一下html5中history有哪些属性和API,我们用到了其中2个方法(pushState、replaceState),来根据状态存储的数据判断是否触发返回事件
1、window.history.length - 历史记录长度 (只读)
2、window.history.state - 历史记录状态 (只读)
3、window.history.go(num) - 回到指定的历史记录(参数num可以是正/负)
4、window.history.back() - 回到上一个历史记录
5、window.history.forward() - 回到下一个历史记录(前提当前历史记录不是最新的)
6、window.history.pushState(state, title, newUrl) - 新增一个历史记录(路径等于当前的url + newUrl )
7、window.history.replaceState(state, title, newUrl) - 替换当前的历史记录路径(路径等于当前的url + newUrl )

监听事件:window.onpopstate

pushState和replaceState作用演示:

打开当前页面路径如下(D:/webstorm_workspace/demo-code/eventListenerBack/test.html),历史记录长度1
在这里插入图片描述
点击pushState按钮:创建了一条新的历史记录(新建状态)、历史记录长度2
在这里插入图片描述
pushState按钮的代码如下:

// pushState会新建一条历史记录
pushState = () => {
  let state = {'name': '张三 - pushState'}
  window.history.pushState(state, null, '?pushState')
  console.log('pushState')
  console.log(window.history.state)
}

点击replaceState按钮:替换当前的历史记录(更新状态),历史记录长度2
在这里插入图片描述
replaceState按钮的代码如下:

// replaceState会覆盖当前的历史记录
replaceState = () => {
  let state = {'name': '张三 - replaceState'}
  window.history.replaceState(state, null, '?replaceState')
  console.log('replaceState')
  console.log(window.history.state)
}
监听事件演示

点击返回按钮:会触发监听事件window.onpopstate方法;之前的路径是(D:/webstorm_workspace/demo-code/eventListenerBack/test.html?replaceState),返回到(D:/webstorm_workspace/demo-code/eventListenerBack/test.html)
在这里插入图片描述
返回按钮的代码如下:

// 返回按钮监听
window.onpopstate = (e) => {
  console.log('触发onpopstate方法')
  console.log(historyState)
  // 判断前一个历史记录存储的state数据来确定是否需要改变当前的数据
}
总结

1、什么时候会触发这个监听事件?除了back方法,go和forward方法也可以触发
2、前进后退历史记录需要根据条件判断时,需要绑定监听事件

vue-router模式:vue-router hash模式和html5 history api提供的模式都是不刷新页面来改变页面的内容

演示代码:Html5监听返回

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值