iframe 裡的頁面和父頁面要互相傳資料,難度完全取決於「同不同源」。同域時輕鬆讀寫;跨子域只要設定 document.domain 也能打通;真正完全不同的網域,就只能靠改寫 location.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>
小結
document.getElementById('idName').contentDocument 與 window.frames["iframeName"].document 等價。document.domain = 'xxx.com';。兩個頁面網域不同時,直接存取對方 document 一定失敗。可行的做法是改寫對方網址的 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';
var 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>
小結
parent.location.replace 避免父頁面向伺服器發請求,理論上就不會留下歷史紀錄,但實測無效。結論很實際:前端解決跨域的能力天生受限,hash 輪詢只是權宜之計。真正的跨域資料交換,還是交給伺服器端方案(代理、CORS、JSONP 或訊息佇列)會乾淨得多。而如果是現代專案,postMessage 才是跨域 iframe 溝通的正規途徑。