父页面于iframe通信

2018-7-18 liyangweb.com 李杨 HTML

  • iframe给父页面发送消息

父页面代码

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>index</title>
</head>
<body>
<iframe src="./iframe.html"></iframe>
</body>
<script type="text/javascript">
	window.addEventListener('message',function(event){
         //此处执行事件
         console.log(event.data);
	})
</script>
</html>


iframe代码

<!DOCTYPE html>
<html>
<head>
	<title>iframe</title>
</head>
<body>
<button onclick="clickHere();">hahaha</button>
</body>
<script type="text/javascript">
	function clickHere() {
		window.parent.postMessage({"click":true},'*');		
	}
</script>
</html>



  • 父页面给iframe发送消息

父页面代码

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>index</title>
</head>
<body>
<button onclick="clickHere();">hahaha</button>
<iframe src="./iframe.html" id='iframeId'></iframe>
</body>
<script type="text/javascript">
	function clickHere()
	{
		var frame = document.getElementById('iframeId');
		frame.contentWindow.postMessage({"click":true},'*');
	}
</script>
</html>

iframe代码

<!DOCTYPE html>
<html>
<head>
	<title>iframe</title>
</head>
<body>
</body>
<script type="text/javascript">
window.addEventListener('message',function(event){
    //此处执行事件
    console.log(event.data);
})
</script>
</html>


评论(0) 浏览(131)

Powered by emlog 冀ICP备13011830号-1