uniapp开发h5 监听用户物理返回键 类似拼多多返回后弹窗

uniapp有个onBackPress生命周期  但是h5中只能监听到navbarr左边的返回按钮以及uni.navigateBack() 方法

h5既然监听不到物理返回键,那么用户点击了物理返回键自然会路由返回上一页,那么我们监听路由,由于路由是uni自己封装的,我测试的项目是hash路由,所以我监听了onhashchange事件 ,然后由于

首页===》详情页

遇到的问题

在详情页的onload里面监听hashchange事件,会发现监听到了物理返回,但是会先执行当前vue页面的destroyed函数,再执行物理返回中的操作函数。这样就会导致页面已经跳回上一个页面后才出现提示框。

于是我的做法是:在当前vue页面(A页面)加载时往浏览器历史里备份一份当前的url地址(B页面),此时用户点击返回,就会从B页面跳到A页面,由于这两个页面地址一致,就会产生点击回退却没有效果的错觉。接着回到A页面后,触发监听事件,处理具体的业务流程……

下面是代码:

首页:  /pages/test/test

<template>
	<!-- 首页 -->
	<div>
		<div @click="$jumpTo(`/pages/detail/detail`)" style="height: 40px;background-color: aquamarine;" class="flex justify-center align-center">去详情</div>
	</div>
</template>

<script>
	import { mapState } from 'vuex';
	export default {
		data() {
			return {

			}
		},
		components: {},
		computed: {
			
		},
		onLoad() {

		},
		onShow() {

		},
		methods: {

		}
	}
</script>

<style lang="scss" scoped>
</style>

详情页:/pages/detail/detail

<template>
	<div>

	</div>
</template>

<script>
	
	export default {
		data() {
			return {

			}
		},
		components: {},
		computed: {
		
		},
		onLoad() {
			window.history.pushState(null, null, document.URL + '#1') //往浏览器历史中添加一次记录
			window.onhashchange = (e) => {
				console.log(e);
				uni.showModal({
					title: '提示',
					content: '返回后此页面的操作将不作保留!',
					cancelText: '确定返回',
					confirmText: '留在此页',
					success: (res) => {
						if (res.confirm) {
							window.history.pushState(null, null, document.URL + '#1')
						} else if (res.cancel) {
							window.history.back();
							window.onhashchange = null //这里不取消监听那么上面的history.back()也会触发一次uni.showModal,就会有两个弹窗
						}
					}
				});
			}

		},
		onUnload() {
			window.removeEventListener("popstate", this.browserBack);
		},
		onShow() {

		},
		methods: {
			browserBack() {
				console.log(1);
				// 在这里写弹框
				uni.showModal({
					title: '提示',
					content: '返回后此页面的操作将不作保留!',
					cancelText: '确定返回',
					confirmText: '留在此页',
					success: (res) => {
						if (res.confirm) {
							// 用户选择留在此页,不进行任何操作
						} else if (res.cancel) {
							window.history.back(); // 使用window.history.back()返回上一页
						}
					}
				});
				window.history.replaceState(null, null, document.URL); // 保留此行代码
			},
		}
	}
</script>

<style lang="scss" scoped>
</style>

 如果是history路由的话,那么就监听popstate事件,和上面一个逻辑,可以参考这个老哥文章

无用的小技巧:

如果想禁用一个页面的返回操作,只需要在这个页面的历史记录中写入大量的历史。比如:

for(var i = 0 ; i < 20 ; i++){history.pushState(null,null)
}

相对的,取消禁用就需要以下代码 + 一个手动回退

history.go(-20)
location.reload()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柑橘乌云_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值