前情提要:
1、使用webview的页面需要是nvue,否则没有 sWebViewRef.value.evalJS() 方法;
2、需要自己安装npm i y_uniwebview,官方的 引入https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js脚本存在冲突,会报错
第一步,在 h5 项目中安装y_uniwebview插件
安装: npm i y_uniwebview 引入: import y_uni from "y_uniwebview"
第二步,h5 代码,接收app信息和向app发送信息
接收到app信息:{{ appMsg }}
import y_uni from "y_uniwebview"
import { ref } from 'vue';
const appMsg = ref('');
// app信息触发方法
window.appCallBack = (val) => {
appMsg.value = val
console.log('app发送过来的数据---', val)
}
let count = 0;
// 向app发送信息
function postMessage(type) {
console.log('h5发送信息');
// 发送信息
y_uni.webView.postMessage({
data: {
msg: `h5信息 ${count++} 次`
}
});
}
第三步、app页面,接收h5信息和向h5发送信息
注意,这里需要用nvue,否则会没有 sWebViewRef.value.evalJS() 导致报错
接收到h5信息:{{h5Msg}}
import {computed, ref} from 'vue';
const sWebViewRef = ref()
const h5Msg = ref('');
// 接收h5信息
function handleMessage(event) {
// 接收webview发送的消息
h5Msg.value = event.detail.data[0].msg;
console.log('收到 h5 消息: ' + h5Msg);
}
let count = 0;
// 向 h5 发送信息
function postMsg(msg) {
console.log('app发送信息')
sWebViewRef.value.evalJS(`appCallBack('app信息 ${count++} 次')`)
}
const webViewStyle = computed(() => {
let width = 0;
let height = 0;
uni.getSystemInfo({
// 获取当前设备的具体信息
success: sysinfo => {
width = sysinfo.windowWidth - 100;
height = sysinfo.windowHeight - 100;
}
})
return {
width: width + 'px', height: height + 'px'
}
})
总结
到此这篇关于uni-app中app和webview的h5通信的文章就介绍到这了,更多相关uni-app app和webview的h5通信内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
