uniapp向webview中发送数据,通过打开的src在src后面拼接上想要的传送的数据,类似于前端的query的传值方式
 <web-view @message="message"  src="/hybrid/html/index.html?userId=335656"></web-view>

在webview也就H5页面中,通过window.location.herf可以获取到url,通过window.location.search可以获取到?后面的数据,进行处理。

webview向uniapp端发送数据,一定在H5页面先引入uni的js文件,这样才可以使用uni的部分api,通过postMessage,方法,向uniapp端发送数据,webview上使用 @message进行监听
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
	</head>
	<body>
		titiifdfss
		<button type="button" onclick="test()">test</button>
	</body>
	//在H5页面中需要引用下面的js才能在使用uni的api
	<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
	<script type="text/javascript">
		//监听js是否加载完毕,在页面加载完成 并且uni的集成方法加载完成后调用
		document.addEventListener('UniAppJSBridgeReady', function() {
		      uni.postMessage({
		              data: {
		                   action: '这是我传送的消息'
		              }
		        });//传递的消息信息,必须写在 data 对象中。
		 });
		function test(){
		//或者返回出页面重定向到uni项目其他的页面中
		 //      uni.redirectTo({
		             // url:'/pages/login/login'
			   // })
		//通过点击像webview的页面传送数据
			        uni.postMessage({
			            data: {
			                action: '相册'
			            }
			        });
		}
	</script>
</html>

webview页面监听的方法

<template>
	<view>
		  <web-view @message="message"  src="/hybrid/html/index.html?userId=335656"></web-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		methods: {
			 message(event){
			        console.log('接收到消息',event.detail.data)
					if(event.detail.data[0].action=='相册'){
					//写一些调用uni的api的方法,或者逻辑
						uni.chooseImage({
						    count: 6, //默认9
						    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
						    sourceType: ['album'], //从相册选择
						    success: function (res) {
						        console.log(JSON.stringify(res.tempFilePaths));
						    }
						});
					}
			    }
		}
	}
</script>
<style>
</style>

uniapp中webviwe官方介绍地址:https://uniapp.dcloud.io/component/web-view

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐