在微信环境中,可通过微信JS-SDK的wx.miniProgram.navigateTo方法实现H5跳转微信小程序(包括uniapp开发的小程序)。以下是具体实现步骤:
1. 引入JS-SDK
在H5页面中引入微信JS-SDK(建议使用最新版本):
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
2. 初始化配置
通过后端接口获取签名配置,并初始化:
wx.config({
  debug: false, // 生产环境建议关闭
  appId: '公众号APPID', // 公众号的appid
  timestamp: 0, // 签名时间戳
  nonceStr: '', // 签名随机串
  signature: '',// 签名
  jsApiList: ['chooseImage'] // 实际不需要具体API,但需填写至少一个
});
3. 执行跳转
在wx.ready中调用跳转方法:
wx.ready(function(){
  wx.miniProgram.navigateTo({
    url: '/pages/target/target' // 小程序页面路径(需在公众号关联的小程序列表中)
  });
});
4. 完整示例
<!DOCTYPE html>
<html>
<head>
  <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>
  <script>
    // 1. 从服务端获取配置(需自行实现ajax请求)
    const configResult = await getWxConfig(); 
    
    // 2. 初始化配置
    wx.config({
      debug: false,
      appId: configResult.appId,
      timestamp: configResult.timestamp,
      nonceStr: configResult.nonceStr,
      signature: configResult.signature,
      jsApiList: ['chooseImage']
    });
    // 3. 跳转小程序
    wx.ready(() => {
      wx.miniProgram.navigateTo({
        url: '/pages/index/index?from=h5' // 支持传递参数
      });
    });
    wx.error(res => {
      console.error('配置失败:', res);
    });
  </script>
</body>
</html>
注意事项:
- 域名要求:H5页面必须设置在公众号的JS安全域名下
- 关联小程序:目标小程序需与公众号关联
- 路径格式:小程序路径需以/开头,如/pages/home/home
- uniapp适配:uniapp编译后的小程序路径可通过uni.navigateTo调试获取
- 兼容性:建议在微信内置浏览器测试,部分安卓机型需开启调试模式
替代方案(无需JS-SDK):
使用<a>标签直接跳转(需已关联小程序):
<a href="weixin://dl/business/?ticket=xxx">跳转小程序</a>
但此方式需要先通过接口获取ticket,且跳转体验不如JS-SDK稳定。
建议优先使用JS-SDK方案,并做好错误处理(如用户未安装小程序时的降级方案)。