WeChat applet-web-View use and communication with the applet

1. What is web-view?

Simply put, it is a small program nested H5 page

web-view official website address

2. How to use web-view

1. Create a page in the applet dedicated to displaying H5

不需要在这个页面做修饰,H5页面会自动铺满
bindmessage属性用来绑定从H5传值过的函数;
注意:传给H5的数据只能拼接在url后面

The code is as follows (example):

<web-view src="H5页面地址?token=XXXX" bindmessage="handlePostMessage" ></web-view>

接收 h5 页面传递过来的参数

 onLoad: function (options) {
    
    },
  handlePostMessage: function (e) {
    
    
    console.log(e.detail.data)
    let resObj = e.detail.data[e.detail.data.length - 1];
//多次传递会是数组的形式,传递一次会push进数组,所以我们需要拿到最新的数据,也就是数组的最后一个子集
    console.log(resObj.message)
  },

2. H5 page

(1) Introduce JSSDK

The code is as follows (example):

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

(2) Determine whether it is in the mini program environment

wx.miniProgram.getEnv(function (res) {
    
    
	if (res.miniprogram) {
    
      
    //小程序环境 ,在此进行相关逻辑处理
    } else {
    
    
    //非小程序环境下逻辑
     console.log('不在小程序中')
    }
})

(3) Get page path parameters

function getQueryString(e) {
    
    
  var t = new RegExp("(^|&)" + e + "=([^&]*)(&|$)", "i"), 
  i = window.location.search.substr(1).match(t); 
  return null != i ? decodeURIComponent(i[2]) : null
}
//调用函数

 let token = getQueryString("token");

(4) Pass value to the applet

向小程序发送消息,会在特定时机(小程序后退、组件销毁、分享)触发组件的 message 事件;

  wx.miniProgram.postMessage({
    
    
     //这里一定要将数据放在dada中
     data: {
    
    
         message: uploadinput.files[0]
     }
   });
  //跳转到小程序页面,触发向小程序发送消息
  wx.miniProgram.redirectTo({
    
    
     url: '/pages/studentWork/scoreInfo/scoreInfo' 
  })

Guess you like

Origin blog.csdn.net/qq_35971976/article/details/128327473