實務專案中很常遇到 iframe 場景:父頁面需要呼叫子頁面的函式,或子頁面需要回呼父頁面的函式。本文以 parent.html 與 child.html 為例說明。
重點在於兩個入口:父頁面透過 window.frames["frameName"] 取得子視窗物件;子頁面則透過 parent 取得父視窗物件。取得視窗物件後,就能直接呼叫對方全域函式。
<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="child.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>
一是 iframe 的 name 屬性必須設定,因為 window.frames 是以 name 為索引的;只給 id 在部分瀏覽器下會取不到。
二是若父頁面與 iframe 屬於不同來源(跨網域),上述寫法會被同源政策阻擋而拋出安全性錯誤。此時需要改用 postMessage 進行跨文件通訊,並在接收端仔細驗證 event.origin。
三是子頁面尚未載入完成時呼叫其函式會失敗,建議在父頁面的 iframe 上監聽 load 事件後再進行互動。