只要專案裡用上了 iframe,遲早會遇到這道題:父頁面想呼叫子頁面的方法,或者子頁面要回頭通知父頁面。這件事在同源前提下非常簡單,關鍵是找對那條指向對方 window 的路徑。
假設 parent.html 內嵌了一個指向 child.html 的 iframe,id 與 name 都叫 childPage。
透過 window.frames 集合,用 name 定位到子視窗,就能直接摸到它全域作用域裡的函數:
window.frames["childPage"].child_click();
子頁面裡的 parent 指向外層視窗,多一層嵌套時則用 top:
parent.parent_click();
父頁面:
<html>
<head>
<script type="text/javascript">
function parent_click() {
alert("來自父頁面");
}
</script>
</head>
<body>
<input type="button" value="調用本頁面函數" onclick="parent_click();" />
<input type="button" value="調用子頁面函數"
onclick='window.frames["childPage"].child_click();' />
<iframe id="childPage" name="childPage" src="inner.html"
width="100%" frameborder="0"></iframe>
</body>
</html>
子頁面:
<html>
<head>
<script type="text/javascript">
function child_click() {
alert("調用的子頁面函數");
}
</script>
</head>
<body>
<input type="button" value="調用父頁面函數"
onclick='parent.window.parent_click();' />
<input type="button" value="調用本頁面函數" onclick="child_click();" />
</body>
</html>
postMessage,而不是想辦法繞過同源限制。onload 後主動向父頁面通報就緒,是更穩健的方向。window.frames 索引的是 name,只設 id 在部分舊瀏覽器上會取不到。如果專案裡 iframe 只是為了隔離第三方內容,那麼優先考慮 sandbox 屬性搭配 postMessage,這才是現代瀏覽器提供的正解。