前情提要:
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发送信息
<template> <view class="avatar-uploader"> <view> <button @click="postMessage">向app发送信息</button> </view> <view> 接收到app信息:{{ appMsg }} </view> </view> </template> <script lang="ts" setup> 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++} 次` } }); } </script>
第三步、app页面,接收h5信息和向h5发送信息
注意,这里需要用nvue,否则会没有 sWebViewRef.value.evalJS() 导致报错
<template> <view> <button @click="postMsg"> 向h5发送信息 </button> <view> 接收到h5信息:{{h5Msg}} </view> </view> <br> <web-view ref="sWebViewRef" src="http://192.168.31.93/" style="" :style="webViewStyle" @on-post-message="handleMessage" ></web-view> </template> <script setup> 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' } }) </script>
总结
到此这篇关于uni-app中app和webview的h5通信的文章就介绍到这了,更多相关uni-app app和webview的h5通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/335497r3m.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容