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_915909064 小时前
iOS 抓包工具有哪些?实战对比、场景分工与开发者排查流程
android·开发语言·ios·小程序·uni-app·php·iphone
2501_915918411 天前
iOS 框架全解析,原生框架与跨平台框架对比、开发应用打包与 App Store 上架实战经验
android·ios·小程序·https·uni-app·iphone·webview
街尾杂货店&1 天前
cssword属性
uni-app
鱼樱前端1 天前
uni-app快速入门章法(二)
前端·uni-app
三天不学习2 天前
uniapp集成语音识别与图片识别集成方案【百度智能云】
百度·uni-app·语音识别
卷Java2 天前
饼状图修复总结
java·spring boot·uni-app·echarts
闲蛋小超人笑嘻嘻2 天前
find数组方法详解||Vue3 + uni-app + Wot Design(wd-picker)使用自定义插槽内容写一个下拉选择器
前端·javascript·uni-app
2501_916007472 天前
前端开发工具都有哪些?常用前端开发工具清单与场景化推荐
android·ios·小程序·https·uni-app·iphone·webview
2501_915909062 天前
iOS 应用上架全流程解析,苹果应用发布步骤、ipa 上传工具、TestFlight 测试与 App Store 审核经验
android·macos·ios·小程序·uni-app·cocoa·iphone