如何从H5跳转到小程序

203 阅读1分钟

使用微信公众号开发文档中的api wx-open-launch-weapp

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="./css/index.css" />
  <script src="./js/vue.min.js"></script>
  <script src="./js/axios.min.js"></script>
  <!-- 调试用的移动端 console -->
  <script src="https://cdn.jsdelivr.net/npm/eruda"></script>
  <script>eruda.init();</script>
  <!-- 公众号 JSSDK -->
  <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<style>
  [v-cloak] {
    display: none;
  }
</style>
<body>
  <div id="app">
    <div id="wineBtn" class="winebtn"></div>
    <button @click="wxLaunchInfo">生成H5跳转小程序的按钮</button>
  </div>
  <script type="text/javascript" src="./js/md5.min.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {},
      created() {        
        this.wxOpenLaunchInit();
      },
      methods: {
        // wx-open-launch-weapp 初始化
        wxOpenLaunchInit() {
          wx.config({
            appId: '公众号的唯一标识',
            timestamp: 0,
            nonceStr: 'nonceStr',
            signature: 'signature',
            jsApiList: ['chooseImage'], // 需要使用的js接口列表
            openTagList: ['wx-open-launch-weapp'], // 需要使用的开放标签列表
          })
        },
        wxLaunchInfo() {
          let jumpBtn = `
            <button class="storeWine">去存取酒</button>
            <style>
              .storeWine {
                width: 100%;
                background: transparent;
                border: none;
                color: #ffffff;
                font-size: 16px;
                font-weight: bold;
                padding: 0px 10px;
                line-height: 40px;
              }
            </style>
          `
          let _params = {
            eleId:"wineBtn", // 元素id
            url: this.urlParams.path, // 跳转小程序的页面路径
            content:jumpBtn, // 自定义的html内容
            appid: `gh_xxxxx`,
            success: (e)=>{
              console.log('成功',e)
            },
            error:(e)=>{
              console.log('失败',e)
            }
          }
          this.wxLaunch(_params)
        },
        wxLaunch(info) {
          let btn = document.getElementById(info.eleId);
          let script = document.createElement("script")
          script.type = "text/wxtag-template"; // 使用script插槽 必须定义这个type
          script.text = info.content // 自定义的html字符串内容
          let html = `<wx-open-launch-weapp style="width:100%;display:block;" username="${info.appid}" path="${info.url}">${script.outerHTML}</wx-open-launch-weapp>`;
          btn.innerHTML = html; // html字符串赋值
          // 点击按钮 正常跳转触发
          btn.addEventListener("launch", function (e) {
            info.success(e);
          });
          // 点击跳转 抛出异常
          btn.addEventListener("error", function (e) {
            info.error(e)
          });
        }
      }
    })
  </script>
</body>
</html>