web-view is a web browser component that can be used to host web pages, and will automatically fill the entire page .
At present, the nested web-view of the mini-program cannot realize real-time communication. The H5 web page can call wx.miniProgram.postMessage({ data: {id:10000} }); Add the @message event on the side to listen to the message, but this event can only be listened to in specific scenarios: back, component destruction, and sharing.
In addition, the H5 web page can also call the WeChat SDK to realize the page jump of the mini program and other functions, such as:
// 页面跳转
wx.miniProgram.switchTab({ url:'/pages/search/search' });
wx.miniProgram.navigateTo({ url:'/pages/search/search' });
wx.miniProgram.reLaunch({ url:'/pages/search/search' });
wx.miniProgram.redirectTo({ url:'/pages/search/search' });
wx.miniProgram.navigateBack();
// 获取当前环境
wx.miniProgram.getEnv((res) => console.log(res.miniprogram));
// 消息通信
wx.miniProgram.postMessage({ data: {id:10000} });
Mini program to add web-view code:
<web-view
src="http://192.168.2.180:8080/activity/midday"
@message="handleMessage">
</web-view>
// 函数监听,必须从data.detail获取通信信息
methods: {
handleMessage(data) {
console.log("接收到handleMessage消息:" + JSON.stringify(data.detail));
}
}
H5 web page code:
// 引入微信SDK
<script>
//判断是否是微信浏览器环境,是则载入js-sdk`
(function(document, window) {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
var script = document.createElement("script");
script.setAttribute('src', '//res.wx.qq.com/open/js/jweixin-1.6.0.js');
document.querySelector('head').appendChild(script);
}
})(document, window)
</script>
// 调用微信小程序能力
todo(){
wx.miniProgram.postMessage({ data: {id:10000} });
wx.miniProgram.navigateTo({ url:'/pages/search/search' });
}
Emphasis again: wx.miniProgram.postMessage cannot achieve real-time communication in the nested web-view of the WeChat applet. Every time the API is called, the data object is only stored in an array. Only when a specific scenario (page back, component destruction , sharing) occurs, the listening event @message in the applet will be triggered. According to the above code execution, the user clicks todo 3 times on the H5 webpage, and the returned data format is as shown in the figure: