iframe 裡的頁面與父頁面之間,同域或跨子域的情況下可以很輕鬆地互相讀寫;完全跨域的情況下,則可以透過改寫 hash 的方式繞道通信。以下是在九個不同(版本)瀏覽器上實測後的結論。
父頁面操作子頁面:
<iframe id="test-iframe" name="test-iframe" src="child.html" scrolling="no" frameborder="0"></iframe>
<script>
window.onload = function () {
/*
* 兩種取得節點的方式都可以。
* 由於 IE6、IE7 不支援 contentDocument 屬性,
* 此處使用較通用的 window.frames["name"] 寫法。
*/
var d = window.frames["test-iframe"].document;
d.getElementsByTagName('h1')[0].innerHTML = 'pp';
alert(d.getElementsByTagName('h1')[0].firstChild.data);
}
</script>
注意:請務必透過 window.onload 之後才去訪問 iframe 內的節點,否則瀏覽器會拋出「拒絕訪問」。實測在 IE8、Firefox 3.6、Opera 11 下,DOMReady 階段也能成功訪問。
子頁面操作父頁面:
<script>
parent.document.getElementsByTagName('h1')[0].innerHTML = 'pp';
alert(parent.document.getElementsByTagName('h1')[0].firstChild.data);
</script>
小結:
1. 實測通過 IE6、IE7、IE8、Firefox 2.0、Firefox 3.0、Firefox 3.6、Chrome 8、Opera 11、Safari 5。
2. document.getElementById('id').contentDocument 等效於 window.frames["iframeName"].document。
3. 跨子域時,需要在父頁面與子頁面的 JS 中分別加上 document.domain = 'xxx.com';。
兩個網頁所在域不同時,無法直接讀取對方的 DOM,只能透過 JS 改變 location 的 hash 值來互相傳遞訊息。
父頁面:
<iframe id="test-iframe" src="https://www.yyy.com/child.html" scrolling="no" frameborder="0"></iframe>
<input type="button" value="send" onclick="sendRequest()" />
<script>
function sendRequest() {
document.getElementById('test-iframe').src += '#a';
}
var interval = window.setInterval(function(){
if (location.hash) {
alert(location.hash);
window.clearInterval(interval);
}
}, 1000);
</script>
子頁面:
<h1>RRRRRR</h1>
<script>
var url = 'https://www.xxx.com/father.html';
oldHash = self.location.hash,
newHash,
interval = window.setInterval(function(){
newHash = self.location.hash;
if (oldHash != self.location.hash) {
document.getElementsByTagName('h1')[0].innerHTML = 'pp';
// 去掉下面這行註解,瀏覽器會提示無權限
// alert(parent.location.href);
parent.location.href = url + '#b';
window.clearInterval(interval);
}
}, 500);
</script>
小結:
1. 實測 IE6、IE7、IE8、Firefox 2.0/3.0/3.6、Chrome 8、Opera 11、Safari 5 中,除 IE6、IE7 外,改動 hash 都會被記錄進瀏覽器 history。
2. 曾嘗試在子頁面用 parent.location.replace 避免父頁向伺服器發請求造成跳轉,理論上瀏覽器就不會記錄歷史,但實測未能奏效。
3. 子頁面無權讀取父頁面的 URL,但可以對父頁面的 URL 進行寫入,所以跨域通信時必須事先知道父頁面的位址。
hash 方案本質上是個繞路的小技巧,受限於同源政策,前端能做的其實很有限。真正複雜的跨域場景,還是交給伺服器端方案(如代理轉發、CORS 標頭)處理更穩妥。若專案環境允許,也建議直接採用 postMessage,它才是現代瀏覽器為跨源視窗通信準備的標準答案。