微信小程序webview给h5传递参数
微信小程序webview给H5传递参数,可以通过以下方法实现:
- 在小程序中使用web-view组件打开H5页面时,可以通过url的query参数传递参数,例如:
<web-view src="https://example.com?param1=value1¶m2=value2"></web-view>
在H5页面中可以通过location.search获取到传递的参数,例如:
var search = location.search.substring(1); // 去掉开头的问号
var params = {};
search.split('&').forEach(function(item) {
var parts = item.split('=');
params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
});
console.log(params.param1); // "value1"
console.log(params.param2); // "value2"
- 如果需要传递复杂的数据结构,可以使用JSON.stringify将数据转换成字符串,再通过url传递,例如:
var data = { name: '张三', age: 18 };
var url = 'https://example.com?data=' + encodeURIComponent(JSON.stringify(data));
在H5页面中可以通过JSON.parse()将字符串转换成数据结构,例如:
var search = location.search.substring(1); // 去掉开头的问号
var params = {};
search.split('&').forEach(function(item) {
var parts = item.split('=');
params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
});
var data = JSON.parse(params.data);
console.log(data.name); // "张三"
console.log(data.age); // 18
- 如果需要在H5页面中动态更新参数,可以使用postMessage方法向web-view组件发送消息,例如:
在小程序中,可以监听web-view组件的message事件,例如:
<web-view src="https://example.com" bindmessage="onMessage"></web-view>
Page({
onMessage: function(event) {
console.log(event.detail.data); // 接收H5页面发送的消息
event.source.postMessage({ name: '李四', age: 20 }, '*'); // 向H5页面发送消息
}
})
在H5页面中,可以使用window.postMessage方法向web-view组件发送消息,例如:
window.addEventListener('message', function(event) {
console.log(event.data); // 接收小程序发送的消息
event.source.postMessage('Hello Mini Program', '*'); // 向小程序发送消息
});
注意:在使用postMessage方法时,需要注意安全性问题,避免被恶意攻击。
原文地址: https://www.cveoy.top/t/topic/g8D 著作权归作者所有。请勿转载和采集!