- 父子页面再同一域名下(同域)
parent.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>父页面</title> <script type="text/javascript"> function changeBg() { document.getElementsByTagName('body')[0].style.backgroundColor="#ff0000"; } function callChild() { frameA.window.changeBg(); frameA.window.document.getElementById("cTip").innerHTML = "父页面发送数据"; } </script> </head> <body> <input type="button" value="改变子页面的背景色" onclick="callChild()" /> <br> 子页面输入内容:<div id="pTip"></div> <iframe name="frameA" src="child.html" frameborder="0"></iframe> </body></html>child.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>子页面</title> <style> #cTip{ color: orange; } </style> <script type="text/javascript"> function changeBg() { document.getElementsByTagName('body')[0].style.backgroundColor="#00ff00"; } function callParent() { parent.window.changeBg(); parent.window.document.getElementById("pTip").innerHTML = document.getElementById("childInput").value; } </script> </head> <body> <div>这是子页面</div> 随便输入点:<input type="text" name="" id="childInput"> <input id="button" type="button" onclick="callParent()" value="把输入内容发送给父页面-改变父页面的背景色" /> <div>接受父页面传来的数据:<span id="cTip"></span></div> </body></html>总结:
父页面调用子页面的方法:
FrameName.window.childMethod();父页面获取子页面的元素:
FrameName.window..window.document.getElementById("cTip").innerHTML 子页面调用父页面的方法
parent.window.parentMethod();子页面获取父页面的元素
parent.window.document.getElementById("pTip").innerHTML- 父子页面跨域传输数据
使用postMessage 进行通信,示例如下:
父页面向子页面发送数据:
let frame = document.getElementById("frame");
//发送数据 data 为数据内容
frame.contentWindow.postMessage( data, "*" );
//接收数据
window.addEventListener("message", function(event) { //此处执行事件 data 为子页面传送过了的数据 let data = event.data;
...... });子页面向父页面发送数据
//发送数据到父页面
window.parent.postMessage(data, '*');
//接收数据window.addEventListener("message", function (e) { console.log("111111---", e.data); var data = e.data;});父子页面接收数据的方式是相同的。
注意事项:
在进行父子页面相互操作的过程中,要确保iframe 加载完成后,在进行操作,否则获取时会出错。判断iframe加载完成:
1、iframe 上用onload事件
2、document.readyState == "complete" 来判断