前情提要:
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通信内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论