萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 跨 Iframe DOM 操作完全指南:父子雙向通信與同源策略

同源策略前提

**只有同源(協議、域名、端口相同)的 iframe 才能互相訪問 DOM**。跨域需用 postMessage。

三個頁面結構

  • 1.html (父頁面):嵌入 a.html (iframeA) 和 b.html (iframeB)。
  • a.html (子頁面 A):含有可被父/兄弟訪問的元素與方法。
  • b.html (子頁面 B):演示訪問父頁面、訪問兄弟頁面 A。

1. 父頁面訪問子頁面

訪問元素

// 方法一:contentWindow.document (推薦,標準)
function getIframeDoc(iframeId) {
  return document.getElementById(iframeId).contentWindow.document;
}

// 使用
getIframeDoc('frameA').getElementById('ooxx').style.backgroundColor = '#f00';

// 方法二:window.frames['name'] (僅能訪問 window 對象,不可直接查元素)
// window.frames['iframeA'].document.getElementById('ooxx') // 同源下可行

調用子頁面方法

// 必須通過 window.frames 或 contentWindow
window.frames['iframeB'].getsFun(); 
// 或
document.getElementById('frameB').contentWindow.getsFun();

2. 子頁面訪問父頁面

// a.html 中
// 訪問父頁面元素
parent.document.getElementById('pox').style.color = '#fff';

// 調用父頁面方法
parent.testP('參數');

// 獲取父頁面變量
var val = parent.someVariable;

3. 兄弟 Iframe 互訪(經父頁面中轉)

// b.html 訪問 a.html
// 方式一:父頁面暴露獲取 iframe 文檔的方法
var aDoc = parent.getIframe('frameA'); // 父頁面定義的函數
aDoc.getElementById('divooxx').style.backgroundColor = '#000';

// 方式二:直接通過父頁面 frames 集合
parent.frames['frameA'].testBA(); // 調用 a.html 的方法

完整代碼示例(三文件)

1.html (父頁面)

<iframe src="a.html" id="frameA" name="frameA"></iframe>
<iframe src="b.html" id="frameB" name="frameB"></iframe>
<script>
function getIframe(id) {
  return document.getElementById(id).contentWindow.document;
}
function testP(msg) { alert('父頁面收到:' + msg); }
</script>

a.html (子頁面 A)

<div id="ooxx">A的元素</div>
<div id="divooxx">供B訪問</div>
<button onclick="parent.testP('來自A')">調用父方法</button>
<script>
function testBA() { alert('A的方法被B調用'); }
</script>

b.html (子頁面 B)

<button onclick="visitSibling()">訪問A的元素</button>
<button onclick="callSiblingMethod()">調用A的方法</button>
<script>
function visitSibling() {
  var doc = parent.getIframe('frameA');
  doc.getElementById('divooxx').style.color = 'red';
}
function callSiblingMethod() {
  parent.frames['frameA'].testBA();
}
</script>

跨域解決方案:postMessage

// 父頁面
window.addEventListener('message', function(e) {
  if (e.origin !== 'https://child-domain.com') return;
  console.log('收到子頁面消息:', e.data);
});

// 子頁面
parent.postMessage({ type: 'resize', height: 500 }, 'https://parent-domain.com');

最佳實踐清單

  1. **同源才能直接操作 DOM**,跨域用 postMessage。
  2. 優先用 iframe.contentWindow.document 獲取文檔對象。
  3. 調用方法用 iframe.contentWindow.fn() 或 window.frames[name].fn()。
  4. 子頁面用 parent 訪問父頁面,top 訪問頂層窗口。
  5. 動態創建的 iframe 需等待 onload 後再操作。
  6. 避免在 iframe 中使用 document.domain 降級同源(已棄用/受限)。
copyright © 萬盛學電腦網 all rights reserved