小程序与H5页面间的相互调用

5,438 阅读1分钟

或许你也有这样的需求:现有的H5页面想在小程序中打开,且当前页面还要调用一些小程序的功能(比如:跳转回到小程序的某个界面、获取地理位置等)。

以下,是我对这种需求的流程总结:

1. 小程序跳转H5

场景:小程序某页面中【去结算】按钮点击跳转到结算H5页面

购物车页面:

//index.wxml
<view class="container">
  <view class="mr200" mark:myMark="last" bindtap="bindViewTap">
    <button mark:anotherMark="leaf">去结算</button>
  </view>
</view>
//index.js
Page({
  data: {
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: `../other/other?url=${encodeURIComponent('http://localhost:3100/order/m_getOrderInfo')}`
    });
  },
  onLoad: function (param) {
    
  },
})

web-view引用外部H5页面

// other.wxml
<!--pages/other.wxml-->
<view class="container">
  <web-view src="{{url}}"></web-view>
</view>
// other.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options.url', decodeURIComponent(options.url));
    this.setData({
      url: decodeURIComponent(options.url),
    })
  },
})

2. H5跳回到小程序

微信开放文档提供了好几种跳转的方法,个人采用了redirectTo方法,具体实现分两步:

H5页面中引入微信提供的jssdk

// body结束前引入
<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>

H5跳转到微信小程序的某个页面

// 调用jssdk方法
window.wx.miniProgram.redirectTo({
    url: ``,
});

3. 问题总结

  1. 开发者工具,web-wiew中引入了H5链接但加载不到,需要如下操作:

设置->项目设置

勾选不校验合法域名等

  1. H5页面中如何判断当前页面是否处在微信小程序中?

微信开放文档中给出了三种方法,个人推荐通过判断userAgent中包含miniProgram字样来判断小程序web-view环境:

  // 判断当前页面是否处在微信中
  function isMiniprogram() {
    const ua = window.navigator.userAgent.toLowerCase();
    let isInMiniprogram = false;

    if (ua.match(/miniProgram/i) == "miniprogram") {
      isInMiniprogram = true;
    }
    return isInMiniprogram;
  }
  1. 参考: 微信开放文档