uniapp中webview和H5网页之间互相传参

uniapp中webview和H5网页之间互相传参

1. uni-app 如何发送数据到 H5?
 1.在 web-view 中只需要通过 URL 就可以向 H5 进行传参 例如在 uni-app 中:
<template>
	<div>
		<web-view :src="webViewUrl" @message="getMessage"></web-view>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				url: '',
			}
		},
		created() {
			this.webViewUrl =
				`http://30.30.127.22:5500/pdf.html?url=${encodeURIComponent(this.url)}` //pdf地址添加参数
		},
		methods: {
			getMessage(e) {
				console.log(e.detail.data)
			},
		},
	}
</script>
2.那么在 H5 中是接收url参数
console.log(getQuery('data'));  //获取 uni-app 传来的值//取url中的参数值
function getQuery(name) {
    // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
    let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    let r = window.location.search.substr(1).match(reg);
    if(r != null) {
        // 对参数值进行解码
        return decodeURIComponent(r[2]);
    }
    return null;
}
2. webview向uniapp传值
1.通过触发UniAppJSBridgeReady监听,使用uni.postMessage传值
<script>
    document.addEventListener('UniAppJSBridgeReady', function() {
        //向uniapp传值
        uni.postMessage({
            data: {
                action: 'h5传递的参数'
            }
        });
        uni.getEnv(function(res) {
            console.log('当前环境:' + JSON.stringify(res));
        });
    });
</script>  
2.uniapp接收参数
//message接受方法
<template>
    <view>
        <web-view :src="url" @message="getMessage"></web-view>
    </view>
</template>
<script>
	export default {
		methods: {
			getMessage(e) {
				//微信小程序
				// #ifdef MP-WEIXIN
				console.log(e.target.data) //多次postMessage的参数数组
				// #endif
				// #ifndef  MP-WEIXIN
				console.log(e.detail.data)
				// #endif
			},
		},
	}
</script>

*网页向小程序 postMessage 时,不是实时发送的,会在特定时机(小程序后退、组件销毁、分享)触发并收到消息。e.detail = { data },data是多次 postMessage 的参数组成的数组
微信小程序官方文档:https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锕舒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值