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

uniapp ios键盘 页面上推_uni-app

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()