uni中webview与H5直接的通讯

突然有个需求,要uni中webview与H5直接进行通讯,本来想的找个例子copy下算了。没想到,很多都不能用啊。至于所谓的什么 @message和  @onPostMessage好像都不行。试验都没任何反应!

算了,自己写吧。我这主要用到2种情况,第一种:uni是H5形式的。第二种:uni是app形式的。都写一下。

第一种:uni H5形式的通讯。

上代码:

H5端

1.先上js加载。

<!-- uni 的 SDK -->
 <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js">
 </script>

2.

document.addEventListener('UniAppJSBridgeReady', function() {
				document.getElementById('startsend').addEventListener('click', function() {
					alert('1234')
					uni.postMessage({
						data: {
							action: '我要传递数据,哈哈哈',
							account: '375130788'
						}
					});
					uni.getEnv(function(res) {
						 alert('当前环境:' + JSON.stringify(res))
					});
				})
			});

这里,就是你的点击事件,添加发送的数据就好。

3.uni中接受数据:

mounted() {
			window.addEventListener("message", this.getReceviceMsg);
},
getReceviceMsg(obj) {
				console.log("H5传值为:", obj.data)
},

这个完事。就这么简单。

第二种:uni app形式的通讯。

他和H5的还不一样,真是费劲,用一样的不好吗?

1.H5页面,一样引js

<!-- uni 的 SDK -->
 <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js">
 </script>

2.一样,添加点击事件,发送消息

 

document.addEventListener('UniAppJSBridgeReady', function() {
				document.getElementById('startsend').addEventListener('click', function() {
					alert('1234')
					uni.postMessage({
						data: {
							action: '我要传递数据,哈哈哈',
							account: '375130788'
						}
					});
					uni.getEnv(function(res) {
						 alert('当前环境:' + JSON.stringify(res))
					});
				})
			});

3.uni webview接收,这里不一样

 

<template>
	<web-view @message="reciveMessage" update-title:false :src=url></web-view>
</template>

加上@message

reciveMessage (data) {
				uni.showToast({
					title: "reciveMessage 接收到消息:" + JSON.stringify(data.detail),
					duration: 2000,
					icon: 'none'
				});
				console.log("接收到消息:" + JSON.stringify(data.detail));
			},

 收工~~~~~

至于webview给h5传数据,就不用多说了吧。直接url后缀加参数,搞定~~~~~~

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值