uniapp与webview通信

webview中html必须引入uni.webview.js文件。uniapp有提供的官方下载地址,去官网找一下。

html 复制代码
<script type="text/javascript" src="js/webview.js"></script>

1、uniapp发消息给webview

uniapp发送代码如下:

html 复制代码
<template>
    <view class="container">
        <web-view :src="webSrc" ref="webview" @onPostMessage="handlePostMessage" @message="handlePostMessage"></web-view>
    </view>
</template>

<script>
    onLoad() {
        /* #ifdef APP-PLUS */
        
        this.webSrc = plus.io.convertLocalFileSystemURL('_www/hybrid/html/camera.html');
        var currentWebview = this.$scope.$getAppWebview()
        setTimeout(()=>{
            this.wv = currentWebview.children()[0];
        },1000)
        
        /* #endif */
    },
    methods: {
         /**
         * TODO 发送消息到webview
         * @param event
         */
        sendWebViewMessage(event){
            this.wv.evalJS("receiveAppMessage('" + JSON.stringify(event) + "')")
        },
    }
</script>

这里省略data中的数据。需要注意的是必须延时一秒再设定this.wv

webview接收代码如下:

复制代码
/**
 * 接收App的消息
 */
function receiveAppMessage(event) {
    console.log("收到消息:" + event);
    event = JSON.parse(event);
}

2、webview发消息给uniapp

webview发送代码如下:

js 复制代码
function sendAppMessage(event) {
    uni.postMessage({
        data: event
    });
}

uniapp接收代码如下:

vue 复制代码
<template>
    <view class="container">
        <web-view :src="webSrc" ref="webview" @onPostMessage="handlePostMessage" @message="handlePostMessage"></web-view>
    </view>
</template>

handlePostMessage: function (event) {
    console.log('接收webview发送的消息:', JSON.stringify(event.detail.data));
},
相关推荐
2501_916008898 小时前
深入解析iOS机审4.3原理与混淆实战方法
android·java·开发语言·ios·小程序·uni-app·iphone
QT.qtqtqtqtqt9 小时前
uni-app小程序前端开发笔记(更新中)
前端·笔记·小程序·uni-app
喵喵虫19 小时前
uniapp修改封装组件失败 styleIsolation
uni-app
游戏开发爱好者81 天前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息1 天前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”1 天前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
局外人LZ2 天前
Uniapp脚手架项目搭建,uniapp+vue3+uView pro+vite+pinia+sass
前端·uni-app·sass
2501_915918412 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview