iframe 嵌入頁面時,父子頁面通信受同源策略限制。本文系統梳理**同域/跨子域直接操作 DOM**、**完全跨域 postMessage 通信**兩大體系,並在 9 款主流瀏覽器 (IE6-IE8, Firefox 2/3/3.6, Chrome 8, Opera 11, Safari 5) 實測兼容性,給出生產級最佳實踐。
<iframe id="test-iframe" name="test-iframe" src="child.html" scrolling="no" frameborder="0"></iframe>
<script>
window.onload = function() {
// 必須在 onload 後訪問,否則 IE6/7 報「拒絕訪問」
// 方式一:window.frames["name"] (通用,含 IE6/7)
var doc = window.frames["test-iframe"].document;
// 方式二:contentDocument (IE8+, 現代瀏覽器)
// var doc = document.getElementById("test-iframe").contentDocument;
doc.getElementsByTagName('h1')[0].innerHTML = '父頁修改子頁標題';
alert(doc.getElementsByTagName('h1')[0].firstChild.data);
};
</script>
<script>
parent.document.getElementsByTagName('h1')[0].innerHTML = '子頁修改父頁標題';
alert(parent.document.getElementsByTagName('h1')[0].firstChild.data);
</script>
父頁面與子頁面主域相同 (如 a.example.com 嵌入 b.example.com) 時,雙方 JS 頭部均需設置:
document.domain = 'example.com'; // 必須設置為相同主域
設置後,雙方視為同源,可直接互訪 DOM。
window.frames["name"].document,不支援 contentDocument。document.getElementById('id').contentDocument 等價於 window.frames["name"].document。當域名完全不同時 (如 xxx.com 嵌入 yyy.com),無法直接操作 DOM,只能通過 location.hash 變化傳遞消息 (老技巧) 或現代 postMessage。
// 父頁面 (xxx.com/father.html)
<iframe id="test-iframe" src="https://www.yyy.com/child.html"></iframe>
<input type="button" value="send" onclick="sendRequest()" />
<script>
function sendRequest() {
document.getElementById('test-iframe').src += '#action=refresh'; // 改變 hash 觸發子頁面輪詢檢測
}
var interval = setInterval(function(){
if (location.hash) { alert('收到子頁回傳: ' + location.hash); clearInterval(interval); }
}, 1000);
</script>
// 子頁面 (yyy.com/child.html)
<h1>RRRRRR</h1>
<script>
var url = 'https://www.xxx.com/father.html';
var oldHash = self.location.hash;
setInterval(function(){
var newHash = self.location.hash;
if (oldHash !== newHash) {
document.getElementsByTagName('h1')[0].innerHTML = 'pp'; // 響應父頁指令
// 回傳:修改父頁 hash (會導致父頁歷史記錄增加)
parent.location.href = url + '#response=ok';
clearInterval(interval);
}
}, 500);
</script>
onhashchange,需輪詢;現代瀏覽器修改 hash 會記錄歷史。// 父頁面
var iframe = document.getElementById('test-iframe');
iframe.onload = function() {
iframe.contentWindow.postMessage({cmd: 'refresh', payload: {id: 123}}, 'https://www.yyy.com');
};
window.addEventListener('message', function(e) {
if (e.origin !== 'https://www.yyy.com') return; // 嚴格驗證源
if (e.data.type === 'result') console.log('子頁返回:', e.data.data);
});
// 子頁面
window.addEventListener('message', function(e) {
if (e.origin !== 'https://www.xxx.com') return;
if (e.data.cmd === 'refresh') {
// 執行刷新邏輯
document.getElementsByTagName('h1')[0].innerHTML = 'pp';
// 回傳結果
e.source.postMessage({type: 'result', data: {status: 'ok'}}, e.origin);
}
});
| 場景 | 推薦方案 | 關鍵點 |
|---|---|---|
| 同域 | 直接 DOM 訪問 | iframe.onload 後用 contentDocument 或 .contents() |
| 跨子域 (主域相同) | document.domain + DOM | 雙方同步設置 document.domain,**注意:標準已廢棄,Chrome 100+ 可能移除** |
| 完全跨域 | postMessage | **唯一標準、安全、異步、不汙染歷史**,嚴格驗證 e.origin |
| 嵌入第三方 (支付/地圖/編輯器) | postMessage SDK | 定義嚴格消息協議,雙方約定 type/payload 結構 |
parent.location.replace 試圖避免歷史記錄 — **無效**,父頁仍會導航。parent.location.href — **跨域拒絕訪問**。iframe 通信是前端工程師必修課,理解同源策略邊界與 postMessage 協議設計,能從容應對嵌入式開發、第三方集成、微前端沙箱隔離等高階場景。