如何判断当前网页环境是微信环境?

可以通过这个获取 window.navigator.userAgent;

//判断H5页面是否在微信/企业微信环境中打开:
var ua = navigator.userAgent.toLowerCase(); // 将用户代理头的值转为小写

 

//判断微信的方法的两种方法:
ua.match(/micromessenger/i) == ‘micromessenger’
/micromessenger/i.test(navigator.userAgent); //结果为true或者false

  

//判断企业微信环境的两种方法:
ua.match(/wxwork/i) == ‘wxwork’
/wxwork/i.test(navigator.userAgent); //结果为true或者false

 

//判断是否为移动端:
window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i); // true:mobile端, false:PC端

封装:

function envjudge() {
  var isMobile = window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i); // 是否手机端
  var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
  var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信

  if (isComWx && isMobile) { //手机端企业微信
     return 'com-wx-mobile'
   }
  else if (isComWx && !isMobile) { //PC端企业微信
    return 'com-wx-pc'
  }
  else if (isWx && isMobile) { // 手机端微信
     return 'wx-mobile';
  }
  else if (isWx && !isMobile) { // PC端微信
     return 'wx-pc';
  }
  else {
     return 'other';
  }

}

//调用

envjudge()

  

 

posted @ 2022-04-14 11:03  高sir不会跳舞  阅读(741)  评论(0编辑  收藏  举报