iframe跨域傳輸資料(一);子頁面訪問主框架DOM元素;
阿新 • • 發佈:2019-02-15
如果使用同域的方法,瀏覽器判斷A.html 與 B.html 不同域,會有錯誤提示。
Uncaught SecurityError: Blocked a frame with origin “http://localhost” from accessing a frame with origin “http://127.0.0.0“. Protocols, domains, and ports must match.
實現原理:
因為瀏覽器為了安全,禁止了不同域訪問。因此只要呼叫與執行的雙方是同域則可以相互訪問。
不同方式的解決方法如下:
解決方法一:
同域下:
使用 window.top或者window .parent.parent獲取瀏覽器最頂層window物件的引用。
可以使用:window.parent.parent.document最頂層元素的DOM物件
window.parent.parent.document.getElementsByTagName("html")來獲取父頁面的HTML元素。
解決方法二:
不同域名下:
iframe在跨域訪問的時候會有嚴格的要求,比ajax跨域請求還要難解決
瀏覽器判斷是否跨域會根據兩種情況,一個是網頁的協議(protocol),一個就是host是否相同,即,就是url的首部
如:
http: (protocol協議)
www.abcd.com :8080 (host)
使用:document.domain =''
1. 對於這種狀況,ifreme在做跨域的時候,可以通過在父頁面和iframe子頁面同時設定document.domain = 'abcd.com'實現降域。子頁面和父頁面同時設定才會有效果,才會跨域通訊,否則會出錯,而且值要相同。這種方法跨域傳輸資料能夠得到解決。
注意:
1.設定document.doamin,也會影響到其它跟iframe有關的功能。
典型的功能如:富文字編輯器(因為是iframe來做富文字編輯器的)、ajax的前進後退(因為IE67要用到iframe,參見:IE6與location.hash和Ajax歷史記錄)。
2. 設定document.doamin,IE678下,有時獲取location.href時有異常
document.domain ="" 方法只能解決,二級域相同,使用domain方法降域可以實現,如果完全不相同的域,此方法無效
解決方法三:
完全跨域。一級域和二級域都不相同時,想要傳輸資料或獲取父頁面的DOM元素有兩種方法,
是使用jsonp方式,用ajax將值傳輸到父頁面的後臺服務中,缺點是需要後臺服務支援。每次都要呼叫服 務器中的介面
a.com下的a.html,需要嵌入b.com下的b.html。這時建一個靜態頁面c.html將c.html放到a.com伺服器中。b.html在嵌入c.html.這樣,將引數值傳輸到c.html中,c.html就可以使用window.parent.parent訪問a.html所在的頂層window物件,就可以操作父頁面的DOM元素。
例如:
a.html:(所在域:22.22.22.22:2222)
<html>
<body>
<iframe id="_top" width="0" height="0" scroll="no" src="http://11.11.11.11:1111/b.html">
</iframe>
</body>
</html>
b.html:(所在域:11.11.11.11)
<html>
<body>
<iframe id="_top" width="0" height="0" scroll="no" src="http://22.22.22.22:2222/c.html?name='zhangsan'">
</iframe>// 每次通過改變src的值來重新整理c.html將name值傳到c.html中;
</body>
</html>
c.html:(所在域:22.22.22.22:2222)
<html>
<body>
<script>
var url = location.search;//通過URL,獲取引數name值
</script?
</body>
</html>
完整例子:通過傳入top來改變父頁面滾動條的高度。
PS:此案例是在a.html嵌入b.html時,禁用b.html的滾動條情況下,需要傳top值
b.html
<html>
<body>
<iframe id="_top" width="0" height="0" scroll="no" src="">
</iframe>
</body>
<script>
$("#_top").empty().attrt({src:"http://22.22.22.22:2222/c.html?top='300'"});
</script>
</html>
c.html
<html>
<body>
</body>
<script type="text/javascript">
window.onload = function(){
var url_param = GetRequest(),
top_ = "";
if( url_param.top ){
top_ = Number(url_param.top);
}
if ( top_ && top_ != "" && top_ != NaN ){
// 通過window.parent.parent獲取最頂層window物件。
// scroolTo改變瀏覽器的滾動條高度
window.parent.parent.scrollTo(0,top_);
}
// 獲取URL中的引數,放入以個物件中放回
function GetRequest() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
};
</script>
</html>