webview和uniapp交互传值
uniapp页面
<web-view :src="webviewUrl" @message="handleMessage" :update-title="false"></web-view>
export default {
data() {
return {
//通过url给webview传值
webviewUrl:"/hybrid/html/local.html?name=2",
}
},
methods:{
//接收webview传过来的值
handleMessage(evt) {
console.log(evt.detail.data)
},
}
}
webview页面
1.接收uniapp传过来的值:
//取url中的参数值,截取url传过来的参数
let newPath = `${window.location.href}`
let splitURL = newPath.split("?")[1];
function getQuery(name) {
// 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if(r != null) {
// 对参数值进行解码
return decodeURIComponent(r[2]);
}
return null;
}
var namePages = getQuery('name')
console.log(namePages) //2
2.给uniapp传值:
document.addEventListener('UniAppJSBridgeReady', function() {
uni.getEnv(function(res) {
console.log('当前环境:' + JSON.stringify(res));
});
uni.postMessage({
data: {
name:"小明",
age:"20"
},
})
});
注意:
新建webview的页面父级目录(hybrid)一定写在和pages同一级目录下
hybrid——>html——>webview.html