iframe 裡外互相呼叫函數其實非常簡單,掌握之後就能輕鬆實現跨頁面的取值與改值。
存取 iframe 內的函數:
document.getElementById('commentIframe').contentWindow.hasLogined();
// commentIframe 為 iframe 的 id,這行需放在 window.onload 之後執行
1.html:
<a href="#" onclick="window.frames['frame1'].MyNext()">aa</a> <iframe id="frame1" src="2.html" ></iframe>
2.html:
<script language="javascript" type="text/javascript">
function MyNext()
{
alert(1);
}
</script>
其他等價寫法:
self.frames['a'].functionName(param) // 呼叫 iframe 中的 JS 函數 iframe2.showInfo(); // 以 iframe 名稱直接呼叫
假設有 index.html 與 inner.html 兩個頁面,index.html 中的 iframe 指向 inner.html。我們要實現兩件事:父頁面呼叫子頁面的函數,子頁面呼叫父頁面的函數。
index.html:
<html>
<head>
<script type="text/javascript">
function ff() {
alert(">>this is index's js function index.html");
}
</script>
</head>
<body>
<div style="background: lightblue;">
This is index page.
<input type="button" value="run index's function" onclick="ff();" />
<input type="button" value="run inner page's function" onclick='window.frames["childPage"].sonff();' />
</div>
<iframe id="childPage" name="childPage" src="inner.html" width="100%" frameborder="0"></iframe>
</body>
</html>
inner.html:
<html>
<head>
<script type="text/javascript">
function sonff() {
alert(">>this is inner page's js function");
}
</script>
</head>
<body>
<div style="background: lightgreen;">
This is inner page.
<input type="button" value="run index's function" onclick='parent.window.ff();' />
<input type="button" value="run inner page's function" onclick="sonff();" />
</div>
</body>
</html>
· 父→子:window.frames['name']、iframe.contentWindow,或直接以 iframe 的 name 存取
· 子→父:parent.window.xxx();多層嵌套則用 top 取得最外層
· 必須同時設定 iframe 的 id 與 name,因為不同瀏覽器偏好的存取方式不同
· 呼叫前要確認 iframe 內容已載入完成,否則會拿到 undefined
· 若 iframe 與主頁面不同源,上述存取會被同源政策阻擋,此時只能改用 postMessage 溝通