iframe 子頁面與父頁面通信根據 iframe 中 src 屬性是同域鏈接還是跨域鏈接,通信方式也不同
一、同域下父子頁面的通信
父頁面 parent.html
<html>
<head>
<script type="text/javascript">
function sayParent(){
console.log("parent.html");
}
function callChild(){
// myFrame 是 iframe 標簽的 name 屬性值
window.myFrame.window.sayChild(); // 調用子頁面的 sayChild() 方法
window.myFrame.window.document.getElementById("button").value = "調用結束"; // 獲取子頁面 button 的屬性
window.myFrame.window.document.body.offsetHeight; // 獲取子頁面 body 高度
}
callChild() // 調用子頁面的方法
</script>
</head>
<body>
<input id="button" type="button" value="調用child.html中的函數say()" onclick="callChild()"/>
<iframe name="myFrame" src="child.html"></iframe> <!-- 一定要有 name 屬性 -->
</body>
</html>
子頁面 child.html
<html>
<head>
<script type="text/javascript">
function sayChild(){
console.log("child.html");
}
function callParent(){
window.parent.window.sayParent(); // 調用父頁面的 sayParent() 方法
window.parent.window.document.getElementById("button").value = "調用結束"; // 獲取父頁面 button 的屬性
window.parent.window.document.body.offsetHeight; // 獲取父頁面 body 高度
}
callParent() // 調用父頁面的方法
</script>
</head>
<body>
<input id="button" type="button" value="調用 parent.html 中的 say() 函數" onclick="callParent()"/>
</body>
</html>
方法調用
父頁面調用子頁面方法:window.FrameName.window.childMethod();
子頁面調用父頁面方法:window.parent.window.parentMethod();
另一種獲取子頁面方法
// 原生 JS 獲取方式:
var frameWin = document.getElementById("ifr").contentWindow;
// jQuery 獲取方式:
var frameWin = $('#ifr')[0].contentWindow;
DOM元素訪問
獲取到頁面的 window.document 對象后,即可訪問 DOM 元素
注意事項
要確保在 iframe 加載完成后再進行操作,如果 iframe 還未加載完成就開始調用里面的方法或變量,會產生錯誤。判斷 iframe 是否加載完成有兩種方法:
- iframe 上用 onload 事件
- 用 document.readyState=="complete" 來判斷
二、跨域父子頁面通信方法
如果 iframe 所鏈接的是外部頁面,因為安全機制就不能使用同域名下的通信方式了
父頁面向子頁面傳遞數據
實現的技巧是利用 location 對象的 hash 值,通過它傳遞通信數據。在父頁面設置 iframe 的src 后面多加個 data 字符串,然后在子頁面中通過某種方式能即時的獲取到這兒的 data 就可以了,例如:
在子頁面中通過 setInterval 方法設置定時器,監聽 location.href 的變化即可獲得上面的 data 信息
然后子頁面根據這個 data 信息進行相應的邏輯處理
子頁面向父頁面傳遞數據
實現技巧就是利用一個代理 iframe,它嵌入到子頁面中,并且和父頁面必須保持是同域,然后通過它充分利用上面第一種通信方式的實現原理就把子頁面的數據傳遞給代理 iframe,然后由于代理的 iframe 和主頁面是同域的,所以主頁面就可以利用同域的方式獲取到這些數據。使用 window.top 或者 window.parent.parent 獲取瀏覽器最頂層 window 對象的引用。
iframe 是否加載完成的完美方法
IE 支持 iframe 的 onload 事件,不過是隱形的,需要通過 attachEvent 來注冊
var iframe = document_createElement_x_x("iframe");
iframe.src = "http://www.020cityshop.com";
if (iframe.attachEvent) { // IE瀏覽器識別
iframe.attachEvent("onload",function() {
alert("Local iframe is now loaded.");
});
}
iframe.onload = function() { // 其他瀏覽器識別。但是不能將此代碼寫入 else 里面,因為火狐瀏覽器進不去 else
alert("Local iframe is now loaded.");
};