iframe父子级页面传值支持跨域访问javascript

 欢迎各位朋友!  奋斗

           今天在使用parent.fn()调用父页面方法时发现并没有成功调用到父级iframe中的方法,后来发现是两个iframe并不在同一域名下,在网上查过后,发现H5中message方法恰好支持,闲话不多说了,上代码

父界面

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
		<script type="text/javascript" src="js/cdIframe.js" ></script>
	</head>

	<body>
        <!--注意该页面在打开时不能使用http://192.168.1.222-->
		<iframe src="http://192.168.1.222:8020/mywork1/new_file.html" width="" height="" id="iframe"></iframe>
	</body>
	<script type="text/javascript">
		/*
		 * receiveMessage (type, callback)
		 * type	子页面传值时进行匹配的字段名称
		 * callback(data, node)
		 * node	子页面所传的值
		 * 
		 * */
		receiveMessage("istype", function (data, node) {
			console.log(node)//子页面中所填写类型为"istype"的数据
		})
	</script>

</html>

子页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<script type="text/javascript" src="js/jquery-1.11.3.min.js" ></script>
		<script type="text/javascript" src="js/cdIframe.js" ></script>
		<title></title>
	</head>
	<body>
		<button id="btn">按钮</button>
		<script>
			/*
			 * postMessage(type, data, direction)
			 * param: type content direction
			 * istype	父页面接收时进行匹配的字段名称
			 * top	标记该数据向父级页面传输
			 * 
			 * */
			postMessage("istype", "这是一个句话", "top")
		</script>
	</body>
</html>

以下就是js代码:

/*
 * cdIframe.js
 * iframe中跨域通信
 * 2018-8-9
 * Y J
 * 
 * */
//父窗体中监听消息
function receiveMessage (type, callback) {
	window.addEventListener('message', function(e) {
		if(e.data.type == type){
			callback(e.data, e)
		};
	});
};
//子窗体中监听消息
function postMessage(type, data, direction) {
	var post = {
		type: type,
		data: data
	};
	if(direction == "top"){
		window.parent.postMessage(post, '*');
	}else{
		window.frames[0].postMessage(post,'*');	//若是向子页面传值则使用该句
	};
};

以上就是所有的代码了,如果哪里写的不对还请多多指正。

下载地址:https://gitee.com/yangjunhouse/dome/tree/master/dome-cdIframe

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值