<iframe name="myFrame" src="child.html"></iframe>
<script>
function callChild(){
// 方式1:window.frames["myFrame"] (兼容性最好)
window.frames["myFrame"].window.say();
// 方式2:iframe 元素 contentWindow
document.getElementById("myFrame").contentWindow.say();
// 操作子頁面 DOM
window.frames["myFrame"].document.getElementById("button").value = "我變了";
}
</script>
<script>
function callParent(){
parent.say(); // 或 parent.window.say()
parent.document.getElementsByName("myFrame")[0].style.height = "100px";
}
</script>
window.frames["iframeName"] 或 iframeElement.contentWindow。parent 或 parent.window。window 後同樣使用 document.getElementById() 等。iframe.onload 或 document.readyState==="complete")再操作。受同源策略限制,無法直接訪問 contentWindow.document。需借助 postMessage 或 location.hash 傳遞數據。
// 父頁面
window.addEventListener("message", function(e){
if(e.origin !== "https://child-domain.com") return; // 安全驗證來源
console.log("收到子頁面數據:", e.data);
// 回傳
e.source.postMessage("父頁面確認", e.origin);
}, false);
<iframe src="https://child-domain.com/child.html" id="crossFrame"></iframe>
// 子頁面 (https://child-domain.com/child.html)
window.parent.postMessage({type:"data", payload:"hello from child"}, "https://parent-domain.com");
// 監聽父頁面回應
window.addEventListener("message", function(e){
if(e.origin !== "https://parent-domain.com") return;
console.log("父頁面回應:", e.data);
}, false);
iframe.src = "child.html#data"。setInterval 監聽 location.hash 變化獲取數據。parent.parent (即頂層父頁面) 調用函數。缺點:輪詢消耗資源、URL 歷史記錄污染、長度限制。
// 父頁面 a.example.com
document.domain = "example.com";
// 子頁面 b.example.com
document.domain = "example.com";
// 之後可直接訪問 cross-document DOM
**注意**:現代瀏覽器逐漸棄用 document.domain,推薦用 postMessage。
| 場景 | 推薦方案 |
|---|---|
| 同域 | 直接 contentWindow / parent 互訪 |
| 跨域 (現代瀏覽器) | postMessage + origin 驗證 |
| 跨域 (IE8/9) | location.hash + 代理 iframe |
| 同主域不同子域 | document.domain (謹慎使用) |