h5移动端开发 判断只能在微信浏览器打开

在开发的过程中可能会遇到项目只能在微信浏览器打开的需求,那么只需要在项目的页面添加以下代码即可(单页面应用在入口文件添加即可)。

<script>
  var ua = navigator.userAgent.toLowerCase();
  var isWeixin = ua.indexOf('micromessenger') != -1;
  if (!isWeixin) {
    window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=888"
  }
</script>

当在非微信浏览器中打开时,显示为下图:

如果要求页面内容显示前就跳转到该页面,则需要将以上js写在head标签中即可。


以上内容已完结,以下为补充内容

由于微信端的缓存问题,导致更新页面内容后,页面并没有及时更新,除首页外其他页面html、css、js等内容可以使用增加版本号的方式实现页面更新,即

<script src="//m.test.com/build/activity/js/commons.js?v=20200608"></script>

但由于首页的特殊性(已经发布到内部了,首页地址并不能去修改),所以想到页面重定向的方式来实现首页增加版本号:

<script>
  var ua = navigator.userAgent.toLowerCase();
  var isWeixin = ua.indexOf('micromessenger') != -1;
  if (!isWeixin) {
    window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=888"
  } else {
    var href = window.location.href;
    var stamp = new Date().getTime();
    //如果href中没有stamp版本号,则添加
    if(href.indexOf("stamp=") == -1) {
      window.location.href = href + "&stamp=" + stamp;
    }
  }
</script>

补充
解决微信端页面文件被缓存

posted @ 2020-09-01 15:50  ZerlinM  阅读(708)  评论(0编辑  收藏  举报