HbuildX H5+App监听手机返回键以及webview关闭

//方法写在index.html即可

<!DOCTYPE html>
<html>

<head>
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <style>
    html,
    body {
      background-color: #f2f2f2;
    }
  </style>
 
  <script>

    // 自适应尺寸 1rem=100px
    (function (doc, win) {
      var docEl = doc.documentElement
      var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
      var recalc = function () {
        var clientWidth = docEl.clientWidth
        if (!clientWidth) return
        if (clientWidth >= 750) {
          docEl.style.fontSize = '100px'
        } else {
          docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'
        }
      }
      if (!doc.addEventListener) return
      win.addEventListener(resizeEvt, recalc, false)
      doc.addEventListener('DOMContentLoaded', recalc, false)
    })(document, window)


    //监听HBuildX app返回键
    document.addEventListener('plusready', function () {
      var webview = plus.webview.currentWebview()
      plus.key.addEventListener('backbutton', function () {
        var l = plus.webview.all().length
        if (l > 1) {
          //如果webview窗口数大于1则关闭
          webview.close()
        } else {
          webview.canBack(function (e) {
            if (e.canBack) {
              webview.back()
            } else {
              // 首页返回键处理
              // 处理逻辑:1秒内,连续两次按返回键,则退出应用;
              var first = null
              first = new Date().getTime()
              console.log('再按一次退出应用') // 此处可以用自定义提示
              setTimeout(function () {
                first = null
              }, 1000)
              plus.key.addEventListener(
                'backbutton',
                function () {
                  if (new Date().getTime() - first < 1500) {
                    plus.runtime.quit()
                  }
                },
                false
              )
            }
          })
        }

      })
    })

  </script>
  <!-- <script src="./static/js/axios.min.js"></script> -->
  <!-- <link rel="stylesheet" href="./static/css/vant.min.css"> -->
</head>


<body>

  <div id="app"></div>

  <!-- 以下是手动插入的JS -->
  <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

</body>

</html>

Guess you like

Origin blog.csdn.net/Lc_style/article/details/112601371