目的
- webView跟小程序通信;
- 找了非常多的方法;
- 关键还是 developers.weixin.qq.com/miniprogram…
- 官方文档
实现
// 判断是否是微信小程序
function isWechatMiniProgram() {
const ua = navigator.userAgent.toLowerCase();
// 微信小程序的 webview User Agent 中包含 "miniprogram" 标识
return ua.includes('miniprogram');
}
function handleMessage () {
// 判断是否是微信小程序
if (isWechatMiniProgram()) {
wx?.miniProgram?.postMessage({ data: { videoUrl: 'xxxxx' } });
// 这里是关键
wx.miniProgram.redirectTo({
url: '/pages/webview/webview',
});
}
}
小程序中
<!--index.wxml-->
<web-view src="{{url}}" bindmessage="handleMessage"></web-view>
Page({
data: {
url: 'xxxx',
},
onLoad() {
this.checkAndRequestAuth();
},
handleMessage(event) {
console.log('收到 webview 的消息:', event.detail.data);
// 处理消息
const obj = event.detail.data[0];
},
总结
只有在调用 wx.miniProgram.redirectTo(或类似的跳转方法)时,web-view 中的 postMessage 才会触发小程序的 bindmessage 事件。这是因为微信小程序的 postMessage 机制设计为在页面跳转或后退时才会传递消息