The iframe element is the document within the document.
window object: The browser will create a corresponding window object when it opens an HTML document. However, if a document defines one or more frames (that is, contains one or more frame or iframe tags), the browser will create a window object for the original document, and then create additional window objects for each iframe. Additional window objects are child windows of the original window.
contentWindow: refers to the specified iframe or the window object where the iframe is located
Demo1
parent page fu.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>父页面</title> </head> <body> <input type=button value="调用子页面中的函数childSay函数" onclick="callChild()"> <iframe id="myFrame" src="zi.html"></iframe> <script type="text/javascript"> function parentSay() { alert("我是父页面中的方法"); } function callChild() { document.getElementById("myFrame").contentWindow.childSay(); } </script> </body> </html>
child page zi.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>子页面</title> </head> <body> <input type=button value="调用父页面中的parentSay()函数" onclick="callParent()"> <script type="text/javascript"> function childSay() { alert("我是子页面的say方法"); } function callParent() { parent.parentSay(); } </script> </body> </html>
Demo2
parent page iframe1.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>父页面与子页面之间的调用</title> </head> <body> <iframe src="http://localhost/iframe/iframe3.html" id="iframe3"></iframe> <iframe src="http://localhost/iframe/iframe2.html" id="iframe2"></iframe> <div>我是父页面</div> <script type="text/javascript"> var iframe2=document.getElementById('iframe2'); iframe2.onload=function(){//父页面调用子页面中的方法 iframe2.contentWindow.b(); }; function test2() { console.log("我是父页面中的方法,在子页面中调用的"); return iframe2; } </script> </body> </html>
child Page iframe2.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>子页面</title> </head> <body> <div id="test">aaa</div> <div>子页面</div> <script type="text/javascript"> //子页面iframe2.html调用父页面iframe1.html的函数: parent.test2(); function b(){ console.log("我是子页面iframe2"); } function c() { console.log("iframe3页面调用iframe2页面"); } </script> </body> </html>
Sub-page iframe3.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>iframe3</title> </head> <body> <script type="text/javascript"> var iframe2=parent.test2(); iframe2.contentWindow.c();//iframe3调用iframe2中的方法 </script> </body> </html>
Demo2 also implements mutual calls between sub-pages.