首先說明一下,iframe 通信分為同域通信和跨域通信兩大類。
一、同域通信
所謂同域通信,是指在 https://localhost/demo/iframe/iframeA.html 下的 a.html 頁面嵌套 iframe。
比如:<iframe src="https://localhost/demo/iframe/iframeB.html" id="iframeA" name="iframeA"> 的 B.html 頁面,這兩個頁面之間進行數據通信。比如我想在父頁面 A.html 調用子頁面中的函數,很容易想到或者 google 一下:document.getElementById('iframeA').contentWindow.b(); 這種方法,其中 b 是子頁面 B.html 中的一個函數。但這樣調用有個問題讓我糾結了很久:既然我在子頁面明明定義了這麼一個函數,為什麼在火狐下會報這樣的錯誤?如下:

b 不是個函數。但我在子頁面明明定義了這個函數,那麼為什麼會報這樣的錯誤呢?經過仔細分析及 google,發現有這麼一個問題需要理解:當 iframe 還沒有加載完成時,我就去執行這個 js,就會報這樣的錯誤。於是就試著在火狐下用 iframe.onload 這個函數進行測試,果然沒有報錯,是正確的,所以就確定了這個問題。因此就想寫個兼容 IE 和火狐、google 的函數,用來確認 iframe 已經加載完成,其實就是給個回調函數來調用上面那個方法。
綜合上面的思路,就可以寫出這樣的代碼:
<iframe src="https://localhost/demo/iframe/iframeB.html" id="iframeA" name="iframeA"></iframe> <div id="topName">topNddddddddddddddddame</div> <script> function A(){ alert("A"); } var iframe = document.getElementById('iframeA'); iframeIsLoad(iframe,function(){ var obj = document.getElementById('iframeA').contentWindow; obj.b(); }); function iframeIsLoad(iframe,callback){ if(iframe.attachEvent) { iframe.attachEvent('onload',function(){ callback && callback(); }); }else { iframe.onload = function(){ callback && callback(); } } } </script> B.html 代碼如下:
var b = function(){ alert("B"); } 子頁面調用父頁面的函數很簡單,只要這樣搞就 OK 了:window.parent.A();
子頁面取父頁面元素的值:window.parent.document.getElementById("topName").innerHTML 等方法。
二、iframe 跨域通信。
iframe 跨域訪問一般分為兩種情況,第一種是同主域、不同子域的跨域。第二種是不同主域跨域。
1、同主域下面、不同子域之間的跨域,可以通過 document.domain 來設置相同的主域來解決。
假如現在我有個域 abc.example.com 下有個頁面叫 abc.html,頁面上嵌套了一個 iframe,如下:<iframe src="https://def.example.com/demo/def.html" id="iframe2" style="display:none;"></iframe>,我想在 abc 域下的 abc.html 訪問 def 域下的 def.html。我們都知道,由於安全性,瀏覽器的同源策略限制了 js 不能操作頁面不同域、不同協議、不同端口的頁面,所以就要解決跨域訪問了。假如父頁面 abc.html 有個 js 函數:function test(){console.log(1);}; 我想在子頁面調用這個函數,還是按照上面的同域方式調用 parent.test(); 這樣,通過在火狐下看,已經跨域了。解決的辦法是:在各個 js 函數頂部加一句 document.domain = 'example.com',就可以解決了。
abc.html 代碼如下:
<iframe src="https://def.example.com/demo/def.html" id="iframe2" style="display:none;"></iframe> // 跨域 子頁調用父頁的 函數 (假設是下面test函數) document.domain = 'example.com'; function test(){console.log(1);}; def.html 代碼如下:
/* * 子頁調用父頁的方法 */ document.domain = 'example.com'; //window.top.test(); window.parent.test();
還是這兩個頁面,我想父頁調用子頁,如下方法:
a.html 代碼如下:
/* * 跨域 父頁想調用子頁的的函數 */ document.domain = 'example.com'; var iframe = document.getElementById('iframe2'); iframeIsLoad(iframe,function(){ var obj = iframe.contentWindow; obj.child(); }); function iframeIsLoad(iframe,callback){ if(iframe.attachEvent) { iframe.attachEvent('onload',function(){ callback && callback(); }); }else { iframe.onload = function(){ callback && callback(); } } } 假如現在 def.html 頁面有個 child 函數,代碼如下:
document.domain = 'example.com'; function child(){console.log('我是子頁');} 這樣就可以跨域調用了,不管是子頁面調用父頁面,還是父頁面調用子頁面,一切 OK!
2、不同主域跨域;
雖然 google 上有幾種方法解決不同主域上的跨域問題,有通過 location.hash 方法,或者 window.name 方法,或者 html5 及 flash 等等,但我覺得下面這種 iframe 方法值得學習一下。
如下圖所示:域 a.com 的頁面 request.html(即 https://a.com/demo/ajax/ajaxproxy/request.html)裡面嵌套了一個 iframe 指向域 b.com(https://b.com/demo/ajax/ajaxproxy/response.html)的 response.html,而 response.html 裡又嵌套了域 a.com 的 proxy.html。

思路:要實現 a.com 域下的 request.html 頁面請求域 b.com 下的 process.php,可以將請求參數通過 url 傳給 response.html,由 response.html 向 process.php 發起真正的 ajax 請求(response.html 與 process.php 都屬於域 b.com),然後將返回的結果通過 url 傳給 proxy.html,最後由於 proxy.html 和 request.html 是在同個域下,所以可以在 proxy.html 利用 window.top 將結果返回給 request.html,完成真正的跨域。

ok,先看看頁面結構
a.com 域下有:
request.html
proxy.html
b.com 域下有:
response.html
process.php
先來看看 request.html 頁面如下:
<!DOCTYPE HTML> <html> <head> <title> New Document </title> </head> <body> <p id="result">這裡將會填上響應的結果</p> <a id="sendBtn" href="javascript:void(0)">點擊,發送跨域請求</a> <iframe id="serverIf" style="display:none"></iframe> <script> document.getElementById('sendBtn').onclick = function() { var url = 'https://b.com/demo/ajax/ajaxproxy/reponse.html', fn = 'GetPerson', //這是定義在response.html的方法 reqdata = '{"id" : 24}', //這是請求的參數 callback = "CallBack"; //這是請求全過程完成後執行的回調函數,執行最後的動作 CrossRequest(url, fn, reqdata, callback); //發送請求 } function CrossRequest(url,fn,reqdata,callback) { var server = document.getElementById('serverIf'); server.src = url + '?fn=' +encodeURIComponent(fn) + "&data=" +encodeURIComponent(reqdata) + "&callback="+encodeURIComponent(callback); } //回調函數 function CallBack(data) { var str = "My name is " + data.name + ". I am a " + data.sex + ". I am " + data.age + " years old."; document.getElementById("result").innerHTML = str; } </script> </body> </html> 這個頁面其實就是要告訴 response.html:我要讓你執行你定義好的方法 GetPerson,並且要用我給你的參數 '{"id" : 24}'。response.html 純粹負責把 CallBack 這個方法名傳遞給下一位仁兄 proxy.html,而 proxy.html 拿到 CallBack 這個方法名就可以執行了,因為 proxy.html 和 request.html 是同域的。
response.html 代碼如下:
<!DOCTYPE HTML> <html> <head> <title> New Document </title> </head> <body> <iframe id="proxy"></iframe> <script> // 通用方法 ajax請求 function _request (reqdata,url,callback) { var xmlhttp; if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { var data = xmlhttp.responseText; callback(data); } } xmlhttp.open('POST',url); xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8"); xmlhttp.send(reqdata); } // 通用方法 獲取url參數 function _getQuery(key) { var query = location.href.split('?')[1], value = decodeURIComponent(query.split(key + "=")[1].split("&")[0]); return value; } //向process.php發送ajax請求 function GetPerson(reqdata,callback) { var url = 'https://b.com/demo/ajax/ajaxproxy/process.php'; var fn = function(data) { var proxy = document.getElementById('proxy'); proxy.src = "https://a.com/demo/ajax/ajaxproxy/Proxy.html?data=" + encodeURIComponent(data) + "&callback=" + encodeURIComponent(callback); }; _request(reqdata, url, fn); } (function(){ var fn = _getQuery('fn'), reqdata = _getQuery("data"), callback = _getQuery("callback"); eval(fn + "('" + reqdata +"', '" + callback + "')"); })(); </script> </body> </html> 這裡其實就是接收來自 request.html 的請求,得到請求參數和方法後,向服務器 process.php 發出真正的 ajax 請求,然後將從服務器返回的數據以及從 request.html 傳過來的回調函數名傳遞給 proxy.html。
接下來看看 php 代碼如下,其實就是想返回一個 json 數據:
<?php $data = json_decode(file_get_contents("php://input")); header("Content-Type: application/json; charset=utf-8"); echo ('{"id" : ' . $data->id . ', "age" : 24, "sex" : "boy", "name" : "huangxueming"}'); ?> 最後就是 proxy.html 代碼:
<!DOCTYPE HTML> <html> <head> <title> New Document </title> </head> <body> <script> function _getUrl(key) {//通用方法,獲取URL參數 var query = location.href.split("?")[1], value = decodeURIComponent(query.split(key + "=")[1].split("&")[0]); return value; } (function() { var callback = _getUrl("callback"), data = _getUrl("data"); eval("window.top." + decodeURIComponent(callback) + "(" + decodeURIComponent(data) + ")"); })(); </script> </body> </html> 這裡也是最後一步了,proxy 終於拿到了 request.html 透過 response.html 傳過來的回調函數名,以及從 response.html 直接傳過來的響應數據,利用 window.top 執行 request.html 裡定義的回調函數。
三、iframe 高度自適應的問題。
iframe 高度自適應分為兩種,一種是同域下自適應,另外一種是跨域下自適應,下面我們來看看同域下 iframe 高度自適應的問題。
1. 同域下 iframe 高度自適應的問題:
思路:獲取被嵌套的 iframe 元素,通過 JavaScript 取得被嵌套頁面的最終高度,然後在主頁面進行設置來實現。
假如我們 demo 有 iframe1.html 和 iframe2.html。
下面貼上 iframe1.html 代碼如下:
<!DOCTYPE HTML> <html> <head> <title> New Document </title> <style> *{margin:0;padding:0;} </style> </head> <body> <iframe src="https://a.com/demo/ajax/iframeheight/iframe2.html" style="width:100%;border:1px solid #333;" frameborder="0" id="iframe"></iframe> <script> window.onload = function() { var iframeid = document.getElementById('iframe'); if(iframeid && !window.opera) { if(iframeid.contentDocument && iframeid.contentDocument.body.offsetHeight) { iframeid.height = iframeid.contentDocument.body.offsetHeight; }else if(iframeid.Document && iframeid.Document.body.scrollHeight){ iframeid.height = iframeid.Document.body.scrollHeight; } } } </script> </body> </html> iframe2.html
<!DOCTYPE HTML> <html> <head> <title> New Document </title> <style> *{margin:0;padding:0;} </style> </head> <body> <div style="height:500px;"></div> </body> </html> 這樣就可以動態設置 iframe1 頁面的高度為 iframe2 的高度了。
2. 跨域下 iframe 高度自適應的問題。
首先我們知道,iframe 跨域我們不能用上面 js 的方式來控制了,所以我們只能借助一個中間頁。我們可以在 a.com 域下 iframe1.html 頁面嵌套一個 b.com 域下的 iframe2.html 頁面,然後我在 iframe2.html 頁面嵌套一個和 iframe1.html 相同域的 iframe3.html 頁面,這樣的話 iframe1.html 和 iframe3.html 就可以無障礙地進行通信了,因為頁面 iframe2.html 嵌套 iframe3.html,所以 iframe2.html 可以改寫 iframe3.html 的 href 值。
iframe1 中的內容:
iframe1.html 內容主要接收 iframe3.html 頁面傳過來的內容並且去完成相應的操作。iframe1.html 代碼如下:
<iframe src="https://b.com/demo/ajax/iframeheight/iframe2.html" style="width:400px;height:200px;" id="iframe"></iframe> <script> var ifr_el = document.getElementById("iframe"); function getIfrData(data){ ifr_el.style.height = data+"px"; } </script> iframe2.html 中的內容:
iframe2.html 的內容是怎麼把值傳給 iframe3.html 頁面?剛才說了,是將值傳遞到 iframe3.html 頁面的 href 中,所以只要修改 iframe 的 src 就可以,因為不用刷新 C 頁面,所以可以用 hash 的方式傳遞給 iframe3.html 頁面。iframe2.html 代碼如下:
<!DOCTYPE HTML> <html> <head> <title> New Document </title> <style> *{margin:0;padding:0;} </style> </head> <body> <iframe id="iframe" src="https://a.com/demo/ajax/iframeheight/iframe3.html" width="0" height="230px"></iframe> <script> var oldHeight = 0, ifr_el = document.getElementById("iframe"); t && clearInterval(t); var t = setInterval(function(){ var height = document.body.scrollHeight; if(oldHeight != height) { oldHeight = height; ifr_el.src += '#' +oldHeight; } },200); </script> </body> </html> 可以看到,默認情況下 iframe1.html 頁面我給 iframe2.html 的高度是 200 像素,但是在 iframe2.html 我給 iframe3.html 高度是 230 像素,那麼正常情況下是有滾動條的。現在我想在 iframe2.html 獲取滾動條的高度,把高度通過 iframe3.html 的 src 裡面傳過去,然後在 iframe3.html 頁面裡獲取這個高度值,傳給 iframe1.html(因為 iframe1.html 和 iframe3.html 是同域的),所以 iframe1.html 能取到這個高度值,再設置下本身的高度就是這個值就 OK 了。
iframe3.html 頁面的唯一功能就是接收 iframe2.html 頁面通過 href 傳進來的值並且傳遞給 iframe1.html 頁面。要拿到 iframe2.html 頁面傳來的值,可以通過一個定時器不停去查看 location.href 是否被改變,但這樣感覺效率很低;還有個方式就是在新的瀏覽器中通過 onhashchange 事件(IE8+、Chrome5.0+、Firefox3.6+、Safari5.0+、Opera10.6+)來監聽 href 的改變。
iframe3.html 代碼如下:
<script> var oldHeight = 0; t && clearInterval(t); var t = setInterval(function(){ var height = location.href.split('#')[1]; if(height && height != oldHeight) { oldHeight = height; if(window.parent.parent.getIfrData) { window.parent.parent.getIfrData(oldHeight); } } },200); </script> 這樣就可以解決通過跨域實現 iframe 自適應高度的問題了。
四、總結
以上就是本文的全部內容,希望對大家的學習工作能有所幫助。如果有疑問可以留言討論。