iframe子頁面與父頁面通信根據iframe中src屬性是同域鏈接還是跨域鏈接,通信方式也不同。
一、同域下父子頁面的通信
父頁面parent.html
<html> <head> <script type="text/javascript"> function say(){ alert("parent.html"); } function callChild(){ myFrame.window.say(); myFrame.window.document.getElementById("button").value="調用結束"; } </script> </head> <body> <input id="button" type="button" value="調用child.html中的函數say()" onclick="callChild()"/> <iframe name="myFrame" src="child.html"></iframe> </body> </html>
子頁面child.html
<html> <head> <script type="text/javascript"> function say(){ alert("child.html"); } function callParent(){ parent.say(); parent.window.document.getElementById("button").value="調用結束"; } </script> </head> <body> <input id="button" type="button" value="調用parent.html中的say()函數" onclick="callParent()"/> </body> </html>
方法調用
父頁面調用子頁面方法:FrameName.window.childMethod();
子頁面調用父頁面方法:parent.window.parentMethod();
DOM元素訪問
獲取到頁面的window.document對象后,即可訪問DOM元素
注意事項
要確保在iframe加載完成后再進行操作,如果iframe還未加載完成就開始調用里面的方法或變量,會產生錯誤。判斷iframe是否加載完成有兩種方法:
1. iframe上用onload事件
2. 用document.readyState=="complete"來判斷
二、跨域父子頁面通信方法
如果iframe所鏈接的是外部頁面,因為安全機制就不能使用同域名下的通信方式了。
父頁面向子頁面傳遞數據
實現的技巧是利用location對象的hash值,通過它傳遞通信數據。在父頁面設置iframe的src后面多加個data字符串,然后在子頁面中通過某種方式能即時的獲取到這兒的data就可以了,例如:
1. 在子頁面中通過setInterval方法設置定時器,監聽location.href的變化即可獲得上面的data信息
2. 然后子頁面根據這個data信息進行相應的邏輯處理
子頁面向父頁面傳遞數據
實現技巧就是利用一個代理iframe,它嵌入到子頁面中,並且和父頁面必須保持是同域,然后通過它充分利用上面第一種通信方式的實現原理就把子頁面的數據傳遞給代理iframe,然后由於代理的iframe和主頁面是同域的,所以主頁面就可以利用同域的方式獲取到這些數據。使用 window.top或者window.parent.parent獲取瀏覽器最頂層window對象的引用。