一。需求:微信小程序在使用webview 时,导航栏是不允许自己修改的。对于左上角的返回按钮,如果相要在返回的时候,弹框确定后再返回,微信小程序是没有api支持。在微信小程序的思路上基本无解。

二。解决办法:用于我们的webview 就是直接使用的微信浏览器。我们是可以使用js 相关的 History API. 主要是通过 设置 history.pushState 这个方法来阻止的。

history.pushState API说明:总共是三个参数,前面两个不用管直接用null 即可,第三个代码跳转页面的地址。

  • 首先进入页面时:执行下面代码
    <script type="text/javascript">
        window.history.pushState(null, null, null)
    </script>

    上面代码的目的就是添加一条历史记录。用于第三个参数为null,则不会发生跳转,但是会添加一条历史记录。然后加上自己的地址,这样就会存在两条历史记录。假如只有一条历史则不会触发 popstate 事件。

  • vue相关代码:

      data() {
         return {
           showConfirmModal: false,
           clickConfirm: false,
           isSaved: false // 是否保存的操作
         }
      },
      mounted() {
        window.addEventListener('popstate', this.handlePopstate)
      },
      beforeDestroy() {
        window.removeEventListener('popstate', this.handlePopstate)
      },
      methods: {
        confirmModal() {
          this.showConfirmModal = false
          this.clickConfirm = true
          uni.navigateBack({
            delta: history.length
          })
        },
        closeModal() {
          this.showConfirmModal = false
          history.pushState(null, null, document.URL)
        },
        handlePopstate() {
          if (!this.clickConfirm && this.isSaved) {
            history.pushState(null, null, document.URL)
            this.showConfirmModal = true
          }
        },
      }

  1. showConfirmModal :  用于显示弹框参数

  2. clickConfirm : 区分是否点击过确定按钮。点击后就一直为true。

  3. 当触发 popstate 事情时,需要先执行下 history.pushState 如果不执行则无法保留当前页面。当点击确定返回时,也会触发该事情,所以需要加一个参数进行控制。

  4. 点击 modal 确定按钮 则需要返回。微信小程序 直接使用。必须使用history.length不然无法退出。因为 history 的长度是大于1的。

    wx.navigateBack({
      delta: history.length
    })

问题咨询:加入QQ群:620302448。或者扫描加入。

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐