c# 浏览器demo html5_Html5监听返回事件

c0fd794b0fdc962c4ec029eb9bfb0127.png

常使用的场景:移动前端

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

436263afa2d5fc7f5c8f4f80fe69dc51.png

点击pushState按钮:创建了一条新的历史记录(新建状态)、历史记录长度2

9f000548ef2f08b2b93fb84b7396fdde.png

pushState按钮的代码如下:

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

点击replaceState按钮:替换当前的历史记录(更新状态),历史记录长度2

58707d0a1313db4effcaa08f8947710d.png

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)

33431b35a57522a61d11a32643919185.png

返回按钮的代码如下:

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

总结

1、什么时候会触发这个监听事件?除了back方法,go和forward方法也可以触发

2、前进后退历史记录需要根据条件判断时,需要绑定监听事件

vue-router模式:https://www.cnblogs.com/xufeimei/p/10745353.html

演示代码:https://github.com/github-gmm/demo-code/blob/master/eventListenerBack/test.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值