iframe跨網域(iframe cross domain)

在大部分的瀏覽器中(chrome、firefox、IE8…),可以使用postMessage和onmessage,去互相傳遞資料postMessage負責丟到不同網域,onmessage則是監聽其他網域丟來的資料。

主要domain:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
<script>
window.onmessage = function(){
console.log(arguments);
};
/*if(window.addEventListener){
window.addEventListener("message",function(){
console.log(arguments);
},false);
}else{
window.attachEvent("onmessage", function(){
console.log(arguments);
});
}*/

</script>

</head>
<body>
<iframe src="http://127.0.0.1/otherDomain.html" id="iframe1"></iframe>
<script>
var win = document.getElementById("iframe1").contentWindow;
setTimeout(function(){
win.postMessage("Hello Sparrow!","http://127.0.0.1/");
},1000);
</script>

</body>
</html>
其他domain(otherDomain.html):
1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
</head>
<body>
<script>
window.onmessage = function(){
console.log(arguments);
};
parent.postMessage("test","http://localhost/");
</script>

</body>
</html>
那麼如果要運行在IE7、IE6底下呢?

這時候可以建立一個proxy.html利用iframe的src嵌入一個proxy.html至於proxy.html需要抓取網址上的參數透過window.frames[“iframe1”]得方式傳遞。動態載入proxy.html,當資料傳遞完畢,將proxy.html的iframe動態移除,監聽事件可以使用onload去監聽。(換句話說,每次傳遞資料都是一次request,另外也可以使用hash”#”去實作)

圖中灰色的proxy.html可透過window.parent.frames[“iframe1”]的方式,而綠色則要使用parent.parent ,或parent.frames[“parent”]。同顏色可透過js語法直接呼叫,不同顏色必須透過proxy.html去抓取url參數,再丟到同網域的頁面。