uniapp中使用iframe

在uniapp中使用iframe而不是webview,是因为webview会自动填充整个页面且层级最高,不方便页面的绘画。
而使用iframe则可以避免这个问题。但因为在uniapp中无法使用h5的windows及document等。
所以我们必须得引入官方的renderjs。[官方文档](https://uniapp.dcloud.io/tutorial/renderjs.html)
下面直接上示例代码

uniapp中

用:data=“data” :change:data = “renderModal.dataChange” 的方式可以监听data值的变化,发生改变时将值传入iframe中,或者用button的click事件 @click=“renderModal.dataClick” 也可触发。但是用了uview中的u-button的click事件却触发不了。

<template>
	<view>
		<view>
	//src:页面地址
			<iframe ref="iframe" id="iframe" :src="..."  class="..."></iframe>
		</view>
		<view :dataItem="dataItem" :change:dataItem = "renderModal.dataChange"></view>
		<button @click="renderModal.dataClick"></button>
	</view>
<template>
<script>
	export default {
		components:{},
		data() {
			return {
				dataItem:''
			},
		},
		methods:{
			receiveRenderData(e){
				//接收的值
				console.log(e)
			}
		}
	}
</script>
<script module="renderModal" lang="renderjs">
	export default {
		data() {
			return {
				dom: '',
			}
		},
		mounted() {
			this.dom = document.getElementById('iframe')
			// 接收iframe传过来的值
			window.addEventListener('message',  (e)=> {
				var data = e.data;
				this.emitData(data.msg) 
			});
		},
		methods: {
			emitData(e) {
				// 将值传到当前页面
			  	this.$ownerInstance.callMethod('receiveRenderData',e)
			},
			// data的值发生改变时会触发dataChange并且将值传到iframe页面中
			dataChange(e) {
				param:{data:e}
				this.dom.contentWindow.postMessage(param,'*')
			}
			// 点击按钮时将值传到iframe页面中
			dataClick() {
				this.dom.contentWindow.postMessage('点击了按钮','*')
			}
		}
	}
</script>	

iframe中

<!DOCTYPE html>
<html lang="en" style="height: 100%;">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
</head>
<body style="height: 100%;margin: 0;" >
   <div></div>
</body>
<script>
	window.onload=()=>{
      getData()
    }
    function getData(){
		let info = {
	       data:'123'
	    }
	    //将值传入uniapp页面
		window.parent.postMessage(info, '*');
	}
	window.addEventListener('message', function (e) {
		//接收uniapp中传过来的值
       	console.log(e.data)
   	})
</script>

总结

这样就完成了uniapp和iframe的子传父和父传子通讯。上面的示例代码可根据自己的实际业务情况进行替换改正。

Logo

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

更多推荐