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>