官网对于uni-app使用web-view的介绍如下:web-view

注意事项提到postMessage方法,这就是web-view向App传递消息的方法,使用如下:

注意H5本身不支持uni-app里面的方法,所以在项目中引入支持调用uni-app方法的库

web-view页面使用:
uni.postMessage({
data: {
action: 'click'
}
});
uni-app接受消息:
getMessage(e) {
console.log('webView传递过来的消息')
const action = e.detail.data[0].action
}
uni-app页面:
computed: {
webViewUrl() {
return `${config.indexUrl}?accessToken=${this.accessToken}`
}
}
web-view网页对url查询字符串进行解析即可得到数据:
/**
* 解析url传递的参数
*/
getQuery(name) {
// 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
const value = window.location.hash.substr(3).match(reg)
// 内网服务
// const value = window.location.search.substr(1).match(reg)
if (value != null) {
// 对参数值进行解码
return decodeURIComponent(value[2])
}
return null
}
const accessToken = this.getQuery('accessToken')
uni-app页面:
methods: {
message(arg) {
console.log(JSON.stringify(arg))
const _funName = 'msgFromUniapp',
_data = {
msg: 'click'
}
const currentWebview = this.$scope.$getAppWebview().children()[0]
currentWebview.evalJS(`${_funName}(${JSON.stringify(_data)})`)
}
}
web-view页面:
window.msgFromUniapp = function(arg) {
console.log(JSON.stringify(arg))
}