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));
},
相关推荐
郑州光合科技余经理1 天前
海外版外卖加盟:总站与分站配送规则怎么分开管
java·开发语言·前端·后端·uni-app·php·ai编程
遗憾随她而去.2 天前
uniApp跨端开发: 解决不同平台显示差异问题
uni-app
程序鉴定师6 天前
2026年深圳小程序/App开发公司技术选型指南:从架构设计到交付标准全维度评估
java·小程序·uni-app·php·objective-c
Q26433650236 天前
【有源码】基于uni-app的旅游行程规划小程序-基于微信小程序的智慧文旅综合服务平台
java·微信小程序·小程序·uni-app·毕业设计·springboot·源代码
qq_316837756 天前
阿里云百炼 fun-asr-realtime uniapp vue3 调用
javascript·vue.js·uni-app
特创数字科技7 天前
uniapp 图片全能处理|全平台支持(鸿蒙、安卓、苹果、web),实现九宫格、水印、滤镜、压缩、拼图
uni-app
2501_916007477 天前
苹果应用商店App Store上架费用标准及原因解析
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张7 天前
苹果App Store上架指南:费用、原理与步骤详解
android·ios·小程序·https·uni-app·iphone·webview
特创数字科技8 天前
【uni-app x】告别系统相机限制!三端通用自定义相机组件:任意布局、静默拍照、录像、水印叠加、连拍回图一次搞定
前端·数码相机·uni-app
Martin -Tang8 天前
uniapp app嵌套webview 弹窗方式
android·ios·uni-app