美文网首页小程序前端开发那些事儿
微信小程序web-view,小程序页面和html交互

微信小程序web-view,小程序页面和html交互

作者: Hush____ | 来源:发表于2021-01-22 15:08 被阅读0次

微信小程序中通过web-view加载html页面前提条件:

1、必须申请认证企业账号,配置业务域名
2、必须发好调用的html页面服务
3、同时服务必须是https的服务

微信开发者工具开发调试可以取消https校验和业务域名的校验。

调试取消https校验和业务域名的校验

一、小程序页面向html页面传参数

1、在发好https的页面服务上面直接拼接
?serial=fa5329afeb5e51cca760c0ed82a7451f&testParam1=1&testParam2=2

<web-view src="http://localhost:9889/gisaddrsel/singleAddrLocate/addressLocate_test.html?serial=fa5329afeb5e51cca760c0ed82a7451f&testParam1=1&testParam2=2" bindmessage="getMessageFromH5" />

2、在对应的html服务中,初始化通过window.location.href获取请求。

获取拼接参数:window.location.href.split("?")[1]

3、测试传参截图

小程序 => html

二、html页面向小程序页面传参数

1、html页面需要引入wx的js

<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>

2、在需要回传的地方,调用wx.miniProgram.postMessage。

注意:正常在回传之前买个页面返回或者组件销毁。
function sendParamByH5(){
    wx.miniProgram.navigateBack({delta: 1})
    wx.miniProgram.postMessage({
        data: {
            testParam1: "1",
            testParam2: "2",
            testParam3: "3"
        }
    })
}

3、在web-view中引用的html触发了小程序后退、组件销毁就会触发bindmessage

<web-view bindmessage="getMessageFromH5" src="http://localhost:9889/gisaddrsel/singleAddrLocate/addressLocate_test?testParam1=1&testParam2=2"  />

4、小程序中:

Page({
  data: {

  },
  onLoad() {
    
  },
  getMessageFromH5(e){
    if (e && e.detail && e.detail.data) {
      console.log(e.detail)
    }
  }
})

5、测试回传截图


html => 小程序

相关文章

网友评论

    本文标题:微信小程序web-view,小程序页面和html交互

    本文链接:https://www.haomeiwen.com/subject/jenszktx.html