先來一段在 B 域頁面中建立隱藏代理 iframe 的程式碼:
<body onload="javascript: setHeight();">
<script>
function setHeight() {
var dHeight = document.documentElement.scrollHeight;
var t = document.createElement("div");
t.innerHTML = '<iframe id="kxiframeagent" src="https://rest.kaixin001.com/api/agent.html#' + dHeight + '" scrolling="yes" height="0px" width="0px"></iframe>';
document.documentElement.appendChild(t.firstChild);
}
</script>
跨域一直是個惱人的問題,上網查過之後才恍然大悟。以下重點在於理解它的實作思路。
問題:A 域名下的 a.htm 透過 iframe 嵌入 B 域名下的 b.html,由於 b.html 的大小不可預知且會變動,需要讓 a.htm 中的 iframe 自適應大小。
本質:這是 JavaScript 的跨域問題。要控制 a.htm 中 iframe 的大小,就必須先讀取 b.html 的尺寸,但 A、B 不屬於同一個域,JS 訪問受限,讀不到 b.html 的大小。
前提:A、B 是合作關係,b.html 能引入 A 提供的 JS。
首先,a.html 透過 iframe 引入 b.html:
<iframe id="aIframe" height="0" width="0" src="https://www.b.com/html/b.html" frameborder="no" border="0px" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes"></iframe>
接著,b.html 引入 A 提供的 JS 檔:
<script language="javascript" type="text/javascript" src="https://www.a.com/js/a.js"></script>
該 JS 先讀取 b.html 的寬高,然後建立一個 src 指向 A 同域中介頁 a_proxy.html 的 iframe,並把讀到的寬高放進 src 的 hash 裡:
<iframe id="iframeProxy" height="0" width="0" src="https://www.a.com/html/a_proxy.html#width|height" style="display:none"></iframe>
a_proxy.html 是 A 域下的中介頁,負責讀取 location.hash 中的 width 與 height,再設定與它同域的 a.html 裡 iframe 的寬高:
var pParentFrame = parent.parent.document.getElementById("aIframe");
var locationUrlHash = parent.parent.frames["aIframe"].frames["iframeProxy"].location.hash;
pParentFrame.style.width = locationUrlHash.split("#")[1].split("|")[0] + "px";
pParentFrame.style.height = locationUrlHash.split("#")[1].split("|")[1] + "px";
如此一來,a.html 中的 iframe 就能自適應為 b.html 的寬高。其他類似的 JS 跨域操作問題,也可以沿著這個「同源中介頁 + hash 傳值」的思路去解決。