uniapp 下,Web-view App 和 h5 (uniapp) 相互通信

vue ⋅ tytrock ⋅ at 2024-03-12 14:39:18 ⋅ 9170 Reads

uniapp官方web-view组件文档


背景:官方文档中,h5端下是用非uniapp做的原生html+javascript做的h5页面,而我做的h5页面也是用uniapp做的,所以在h5端主动通知app端时,直接使用uni.postMessage会报无效。


1、app端

首先在webview原生页面通过$scope获取当前的webview页面,然后执行evalJs()来调用webview h5中的函数,比如下面这个例子就是调用h5中的 getVueMessage 自定义函数。

注意:需要等h5页面加载一段时间再去调用函数,否则有时会无法找到h5页面中的getVueMessage方法而报错,导致h5页面无法接收参数

<template>
    <view>
        <web-view :webview-styles="webviewStyles" ref="webview" :src="'https://tytrock.com/#/pages/index/h5_webview'" @message="callback"></web-view>
    </view>
</template>


<script>
export default {
    data() {
        return {
            sysUser:unigetStorageSync('sysUser'),
	    webviewStyles: {
		progress: {
		    color: '#f99c34'
		}
	    }
	}
    },
    mounted() {
	//向h5端传递参数
        let currentWebview = this.$scope.$getAppWebview();
        let wv = currentWebview.children()[0];
        let data = {
            token:uni.getStorageSync('token'),
            sysUser:this.sysUser
        }
        setTimeout(()=>{
			wv.evalJS(`getVueMessage(${JSON.stringify(data)})`);
		},1000);
    },
    methods: {
        //接收h5端方法
        callback(e){
            console.log(e);
        }
    }
}   }
}


2、h5端

1)、下载webviewjs代码保存至本地 webview,资源url:https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js


2)、在main.js中引入webview.js

import uniwebview from '@/utils/webview.js'


3)、然后就可以在全局进行适用 uni.webview.postMessage进行发送消息

uni.webView.postMessage({
    data: {
        id: 1, // 这是传的参数
    },
});


参考:

https://blog.csdn.net/YhWyl527/article/details/131243288

https://blog.csdn.net/qq_36604863/article/details/125101143


This topic has been mark as Excenllent Topic.
Total Reply Count: 0
    No comments~~
    • publish_typography
    • publish_markdown
    • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
    • publish_image
    • publish_draft
    Ctrl+Enter