h5 打开微信小程序(wx-open-launch-weapp 的使用)

12,077 阅读2分钟

关于 wx-open-launch-weapp 的使用,可以先阅读官方使用文档:开放标签使用步骤

已经实现的示例链接:sourl.cn/6AqdUC

下面是效果图:

0、判断浏览器

摘要:打开微信小程序的开发标签,只适用于微信版本7.0.12及以上的微信手机浏览器。

Q: 只有微信手机浏览器才支持打开mp吗? A: 是的,wx-open-launch-weapp 这个标签应该只有微信浏览器内部定义了。且唤起微信小程序也需要微信的原生支持。

var userAgent = window.navigator.userAgent.toLowerCase();
var is_android = /(android)/.test(userAgent);
var is_iphone = /(iphone|ios)/.test(userAgent);
var is_mobile = is_android || is_iphone;
var is_weixin_browser = /micromessenger/.test(userAgent);

Q:打开小程序有使用条件(微信版本要求为:7.0.12及以上。 系统版本要求为:iOS 10.3及以上、Android 5.0及以上),是否需要做判断? A:做一下把,毕竟现在(2020/07/28)微信的最新版本才7.0.14,至于系统的版本感觉不用判断了。

// 获取微信的版本号,如: 7.0.14
let wechat = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i)

if (wechat) {
  let judgewechat = wechat[1].split('.')

  if (judgewechat[0] >= 7) {
    if (judgewechat[1] >= 0) {
      if (judgewechat[2] >= 12) {
        // 微信版本是 7.0.12及以上
      }
    }
  }
}

1、引入JS

<script src="//res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

2、注入配置信息

wx.config({
  debug: false,
  beta: true,
  appId: data.appid,
  timestamp: data.timestamp,
  nonceStr: data.noncestr,
  signature: data.signature,
  jsApiList: [''], // 备注:这里有一个坑,这项不能是 [],会不显按钮...
  openTagList: ['wx-open-launch-weapp']
})
wx.ready(() => {
  // 显示小程序跳转按钮
})

这里需要注意:

  • jsApiList,这项的值不能是 [],会导致按钮不显示,(2020/07/28 有这个问题)。

3、页面中添加按钮

<div class="btn-wechat-mp__wrap" v-if="false">
  <!-- 显示的按钮 -->
  <div class="btn-wechat-mp--show">
    <div class="btn-wechat-mp__icon">
      <!-- 自定义的组件 -->
      <itv-icon type="i-applet" size="12" />
    </div>
    <span>立即使用</span>
  </div>
  <wx-open-launch-weapp id="launch-btn" username="gh_cb8edfaxxxx" :path="report_params.url">
    <!-- 必须写:占位的按钮 -->
    <script type="text/wxtag-template">
      <style>
        .ctn{width: 120px;height: 40px;}
      </style>
      <div class="ctn"></div>
    </script>
  </wx-open-launch-weapp>
</div>
/* 备注:样式不重要,这里就不换行了 */
.btn-wechat-mp__wrap {
  display: block;width: 120px;height: 40px;margin-top: 30px;position: relative;
  .btn-wechat-mp--show {
    background-color: #3464e0;border-radius: 2px;position: absolute;top: 0;right: 0;left: 0;bottom: 0;display: flex;justify-content: center;align-items: center;color: #ffffff;font-size: 14px;z-index: 0;
    .btn-wechat-mp__icon {
      margin-right: 8px;line-height: 12px;color: #3464e0;box-sizing: border-box;padding: 2px;width: 16px;height: 16px;border-radius: 100%;background: #fff;display: flex;align-items: center;
    }
  }
  #launch-btn {
    z-index: 10;position: absolute;top: 0;right: 0;left: 0;bottom: 0;background: transparent;
  }
}

这里需要注意(良心精华)

  • path 需要添加 .html 后缀,且 path 可以是动态的。
  • 插槽必须写,且内容必须有大小(比如上面的 div.ctn )。vue 中插槽需要用 script 替换。
  • 插槽内不能使用组件,所以可以将需要显示的内容绝对定位(如上面的 div.btn-wechat-mp--show )。

4、调试

因为微信注入配置信息本地无法测试,所以要测试该标签需要在发布到测试环境才可以看到按钮。