NutzCN Logo
问答 盛世在线客服怎么联系开户如何注册会员账号——微95178334 第一财经
发布于 5小时 作者 qq_18288b93 5 次浏览 复制 上一个帖子 下一个帖子
标签:

uni-app中app和webview的h5通信简单步骤
这篇文章主要介绍了如何在nvue页面中使用webview组件,并详细介绍了如何在h5项目中安装和配置npmiy_uniwebview插件,文中通过代码介绍的非常详细,需要的朋友可以参考下
前情提要:
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通信的文章就介绍到这了,

0 回复
添加回复
请先登陆
回到顶部