iframe 本質上就是「文檔中的文檔」。
瀏覽器每打開一個 HTML 文檔,就會建立一個對應的 window 對象。但如果這個文檔裡定義了一個或多個框架(即包含 frame 或 iframe 標籤),瀏覽器除了為原始文檔建立 window 之外,還會為每一個 iframe 額外建立 window 對象,這些額外的 window 就是原始窗口的子窗口。
contentWindow:指向指定的 iframe 所對應的那個 window 對象,是父頁面「向下」操作子頁面的入口。
父頁面 fu.html:
<!DOCTYPE html>
<html lang="en">
<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>
子頁面 zi.html:
<!DOCTYPE html>
<html lang="en">
<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>
父頁面透過 contentWindow 往下叫,子頁面透過 parent 往上叫,這就是最直觀的一組雙向通道。
父頁面 iframe1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>父頁面與子頁面之間的調用</title>
</head>
<body>
<iframe src="https://localhost/iframe/iframe3.html" id="iframe3"></iframe>
<iframe src="https://localhost/iframe/iframe2.html" id="iframe2"></iframe>
<div class="iframe1">我是父頁面</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>
子頁面 iframe2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>子頁面</title>
</head>
<body>
<div id="test">aaa</div>
<div class="iframe2">子頁面</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>
子頁面 iframe3.html:
<!DOCTYPE html> <html lang="en"> <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>
這裡的巧思在於:父頁面把子頁面的 window 對象作為返回值交出去,於是 iframe3 拿到 iframe2 的引用後,就能直接呼叫兄弟頁面的方法。Demo 2 因此同時實現了「父子互調」與「兄弟互調」。
實務上要提醒兩點:一是必須等 iframe 載入完成(onload)再呼叫,否則會拿到 undefined;二是跨域情況下受同源政策限制,無法直接存取對方的 contentWindow。