uni-app中app和webview的h5通信簡單步驟
前情提要:
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發(fā)送信息
<template> <view class="avatar-uploader"> <view> <button @click="postMessage">向app發(fā)送信息</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信息觸發(fā)方法 window.appCallBack = (val) => { appMsg.value = val console.log('app發(fā)送過來的數(shù)據(jù)---', val) } let count = 0; // 向app發(fā)送信息 function postMessage(type) { console.log('h5發(fā)送信息'); // 發(fā)送信息 y_uni.webView.postMessage({ data: { msg: `h5信息 ${count++} 次` } }); } </script>
第三步、app頁面,接收h5信息和向h5發(fā)送信息
注意,這里需要用nvue,否則會沒有 sWebViewRef.value.evalJS() 導致報錯
<template> <view> <button @click="postMsg"> 向h5發(fā)送信息 </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發(fā)送的消息 h5Msg.value = event.detail.data[0].msg; console.log('收到 h5 消息: ' + h5Msg); } let count = 0; // 向 h5 發(fā)送信息 function postMsg(msg) { console.log('app發(fā)送信息') 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通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
警告[vue-router]?Duplicate?named?routes?definition簡單解決方法
這篇文章主要關于介紹了警告[vue-router]?Duplicate?named?routes?definition的解決方法,這個錯誤提示是因為在Vue Router中定義了重復的路由名稱,需要的朋友可以參考下2023-12-12Vue + Webpack + Vue-loader學習教程之相關配置篇
這篇文章主要介紹了關于Vue + Webpack + Vue-loader的相關配置篇,文中通過示例代碼介紹的非常詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03Vue中Layout內(nèi)部布局el-row、el-col的實現(xiàn)
layout是一種非常方便的布局方式,本文主要介紹了Vue中Layout內(nèi)部布局el-row、el-col的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-07-07