vue 定义全局运行环境判断+返回键(支持安卓)

/** main.js */
// 全局环境判断 使用this.ENV 0:浏览器 1:微信h5 2:微信小程序 3:安卓app
const ua = window.navigator.userAgent.toLowerCase()
if (ua.indexOf('micromessenger') !== -1) {
  wx.miniProgram.getEnv(res => { // 异步耗时接口
    if (res.miniprogram) {
      Vue.prototype.ENV = 2 // 微信小程序环境
    } else {
      Vue.prototype.ENV = 1 // 微信h5环境
    }
  })
} else if (ua.indexOf('plus') !== -1) {
  Vue.prototype.ENV = 3 // 安卓app环境
} else {
  Vue.prototype.ENV = 0 // 其他(浏览器)环境
}
// 全局返回键 使用this.BACK()
Vue.prototype.BACK = function() {
  const beforPath = this.$route.fullPath
  setTimeout(() => {
    const afterPath = this.$route.fullPath
    if (beforPath === afterPath) {
      router.push('/') // 无响应统一返回首页
    }
  }, 200)
  if (window.history.length > 1) { // 返回上一级
    if (this.ENV === 3) {
      window.plus.webview.currentWebview().back()
    } else {
      router.back()
    }
  } else { // 返回首页
    router.push('/')
  }
}
原文地址:https://www.cnblogs.com/xiaolinxitong/p/13608318.html