一、uni使用web-view与非uni的H5进行相互通信
1. 第一步
第一种方法:H5端通过引入的方式使用uni提供的方法
-------------index.html-----------------
// index.html
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js"></script>
第二种:直接前往文件所在地进行下载,然后引入使用。<DCloud地址 ↓>
https://gitcode.net/dcloud/hello-uni-app-x/-/blob/alpha/hybrid/html/uni.webview.1.5.5.js
或 直接复制上面的https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js 这条地址直接保存成js文件使用效果一样
2.第二步
引入后直接在 需要传输的H5界面中直接使用
xxx.vue
// 监听uni-app发送的消息
window.addEventListener('message', (event) => {
console.log('监听发送:', event)
});
// 发送信息
uni.postMessage({
data: {
type: 'scanCode'
}
});
3.第三步(看清楚)
我们需要定义一个window中的方法去进行接收。这个方法是随意定义只是用来接收uni传输过来时候触发的方法.。
记住!这个只是随意定义,非有什么特殊含义
xxx.vue
// 传输触发方法
window.appCallBack = (val) => {
console.log('app发送过来的数据---',val)
}
uni-app端
在webview的界面中
设置定时是为了让最后执行,不然会导致空数组 没有该方法
<template>
<view class="webview">
<web-view ref="webviewRef" :src="http" @message="backMessage"></web-view>
</view>
</template>
<script>
export default {
data () {
return {
http:'',
wv:''
}
},
onLoad(val) {
let currentWebview = this.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
setTimeout(() => {
this.wv = currentWebview.children()[0]
}, 1000)
},
methods:{
// 发送数据方法
sendMsg () {
// appScan 就是上面说的 在H5定义在window中的方法!!!
this.wv.evalJS(`appScan('${JSON.stringify(res.result)}')`)
},
// 网页回调
backMessage(event) {
console.log('回传回来的----',event)
if(event.detail.data && event.detail.data.length > 0) {
let dataInfo = event.detail.data[0]
console.log(dataInfo) // 上面h5的参数
let type = dataInfo.type
if(type == 'scanCode') {
console.log('获取到的',dataInfo.url)
}
}
}
}
}
</script>