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

编程入门 行业动态 更新时间:2024-10-28 06:30:53

uniapp开发h5 监听用户物理返回键 <a href=https://www.elefans.com/category/jswz/34/1770819.html style=类似拼多多返回后弹窗"/>

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

更多推荐

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

本文发布于:2023-12-03 16:58:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1656834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类似   物理   用户   uniapp   后弹窗

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!