【轉】js之iframe子頁面與父頁面通訊

 

iframe子頁面與父頁面通訊根據iframe中src屬性是同域連接仍是跨域連接,通訊方式也不一樣。javascript

1、同域下父子頁面的通訊

父頁面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();html

子頁面調用父頁面方法:parent.window.parentMethod();java

DOM元素訪問

獲取到頁面的window.document對象後,便可訪問DOM元素跨域

注意事項

要確保在iframe加載完成後再進行操做,若是iframe還未加載完成就開始調用裏面的方法或變量,會產生錯誤。判斷iframe是否加載完成有兩種方法:瀏覽器

1. iframe上用onload事件安全

2. 用document.readyState=="complete"來判斷函數

2、跨域父子頁面通訊方法

若是iframe所連接的是外部頁面,由於安全機制就不能使用同域名下的通訊方式了。spa

父頁面向子頁面傳遞數據

實現的技巧是利用location對象的hash值,經過它傳遞通訊數據。在父頁面設置iframe的src後面多加個data字符串,而後在子頁面中經過某種方式能即時的獲取到這兒的data就能夠了,例如:代理

1. 在子頁面中經過setInterval方法設置定時器,監聽location.href的變化便可得到上面的data信息htm

2. 而後子頁面根據這個data信息進行相應的邏輯處理

子頁面向父頁面傳遞數據

實現技巧就是利用一個代理iframe,它嵌入到子頁面中,而且和父頁面必須保持是同域,而後經過它充分利用上面第一種通訊方式的實現原理就把子頁面的數據傳遞給代理iframe,而後因爲代理的iframe和主頁面是同域的,因此主頁面就能夠利用同域的方式獲取到這些數據。使用 window.top或者window.parent.parent獲取瀏覽器最頂層window對象的引用。

相關文章
相關標籤/搜索