小程序内前H5 webview 监听导航返回按钮--导航栏

1,532 阅读1分钟

一、因为小程序内嵌H5不支持“navigationStyle”: “custom”——隐藏原生导航栏了,所以有监听页面返回需求的解决办法。

//在index.html中引入js-sdk
<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

// vue h5页面为例
methods: {
    // 插入浏览器历史
    pushHistory(str = 'title', url = '#') {
      let state = {
        title: str,

        url,
      }

      window.history.pushState(state, state.title, state.url)
    },
    goBack() {
      wx.miniProgram.navigateBack()
    },
},

created() {
    let that = this
    // 监听返回
    this.pushHistory()
    window.addEventListener(
      'popstate',
      function(e) {
        //为了避免只调用一次
        that.pushHistory('title1')
        自定义方法, 直接关闭网页或返回小程序上一页
        that.goBack()
      },
      false
    )
},

二、延伸H5特性:Document.hidden 页面是否隐藏 true 或 false

    //用法
    document.addEventListener("visibilitychange", function() {
      console.log( document.hidden );
      // 可以根据document.hidden值,来处理一些音频播放等问题
    });