iframe子页面与父页面通信

iframe子页面与父页面通信

  • 同域下父子页面的通信

父页面parent.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta  http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Document</title>
  <script type="text/javascript">
function say() {
      alert('parent.html')
    }
function callChild() {
    	document.getElementById('myFrame').contentWindow.test()
  	}
  </script>
</head>
<body>
  <button onclick="callChild()">调用child.html中的函数test()</button>
  <iframe id="myFrame" src="child.html"></iframe> 
</body>
</html>

 

子页面child.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta  http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Document</title>
  <script type="text/javascript">
function test() {
      alert('child.html')
}
function callParent() {
      parent.document.getElementById('myFrame').contentWindow.say()
    }
  </script>
</head>
<body>
  <button onclick="callParent()">调用parent.html中的函数say()</button>
</body>
</html>

方法调用

父调子:document.getElementById(‘iframeId’).contentWindow.childMethod();

子调父:parent.document.getElementById(‘iframeId’).contentWindow.parentMethod();

 

  • 跨域父子页面的通信

如果iframe所链接的是外部页面,因为安全机制就不能使用同域名下的通信方式。

父页面www.a.com/parent.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta  http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Document</title>
  <script type="text/javascript">
function sendChild() {
var arr=[0,0,0]
document.getElementById('myFrame').contentWindow.postMessage(arr,"http://www.b.com/child.html");
  	}
	window.addEventListener('message',function(e){  // 接收              
    	//   console.log(e); 
},false) 
  </script>
</head>
<body>
  <button onclick="sendChild()">发送arr数组值</button>
  <iframe id="myFrame" src="http://www.b.com/child.html"></iframe> 
</body>
</html>

子页面www.b.com/child.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta  http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Document</title>
  <script type="text/javascript">
window.addEventListener('message', function (event) {
      console.log(event.data)
top.postMessage('子页面消息收到', ' http://www.b.com/parent.html')    
    }, false)
  </script>
</head>
<body>
</body>
</html>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值