uniapp的webview,H5与uniapp 相互传值的正确方法

1,460 阅读1分钟

首先是uniapp给H5传值

<web-view :src="url" @message="getMessage" @error="onError"></web-view>
1、url是webview的网络请求地址
2、getMessage方法是webview的H5给uniapp传递的值

要想达到UNIAPP给webview的H5传值则要先获取webview的实例


const currentWebview = this.$scope.$getAppWebview()
const wv = currentWebview.children()[0]
	const obj = {
		id: 1,
	}
wv.evalJS(`phoneBack(${JSON.stringify(obj)})`);


其中obj则是给h5传值的内容

webview接收 先要引入uni.webview.1.5.4.js 刚刚UNIAPP 定义了 phoneBack

h5的相关代码

    window.phoneBack = async (arg) => {
      // 填写H5中相关的代码逻辑
    };

H5给UNIAPP 传值

        uni.postMessage({
          data: {
            type: 'photograph'
          }
        });

data则是给UNIAPP传递的一些参数

在uniapp 中已经定义了 getMessage 可以定义方法


getMessage(evt) {
// 可以获取到参数
}

uniapp的代码


<template>
	<view class="content">
		<web-view :src="url" @message="getMessage" @error="onError"></web-view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				
			}
		},
		async onLoad(options) {
			if (options && options.url) {
				this.url = options.url;
			}

			let height = 0; //定义动态的高度变量
			let statusbar = 0; // 动态状态栏高度
			uni.getSystemInfo({ // 获取当前设备的具体信息
				success: (sysinfo) => {
					statusbar = sysinfo.statusBarHeight;
					height = sysinfo.windowHeight;
				}
			});
			let currentWebview = this.$scope.$getAppWebview(); //获取当前web-view
			setTimeout(function() {
				var wv = currentWebview.children()[0];
				wv.setStyle({ //设置web-view距离顶部的距离以及自己的高度,单位为px
					top: statusbar,
					height: height - statusbar, // 我们在这里把webview的高度调整一下

				})
			}, 200); //如页面初始化调用需要写延迟
		},

		onBackPress(e) {
		   定义回退方法
		},

		methods: {
			/**
			 * 接受传值
			 */
			async getMessage(evt) {
                 
			},

			onError(e) {
				console.error('Webview Error:', e)
			},
			// 给webview的H5传值
			sendMsg(params) {
					const obj = {
						id: 1,
						"imgBase64": base64Data,
					}
					wv.evalJS(`msgFromUniapp(${JSON.stringify(obj)})`);
			},
		}
	}
</script>

<style>

</style>

webview H5的代码

    window.msgFromUniapp = async (arg)=>{
      // 接收参数后的方法
    };

// 给webview的传值
        uni.postMessage({
          data: {
            type: 'photograph'
          }
        });