要在父頁面裡操作 iframe 中的 DOM,第一步是拿到 iframe 的文檔對象。這一步的寫法在 IE 與標準瀏覽器之間曾經完全不同。
給定一個 iframe:
<iframe id="myframe"></iframe>
W3C 規範告訴我們,可以通過 DOM 對象的 contentDocument 屬性取得其內部文檔:
doc = document.getElementById('myframe').contentDocument;
但實測表明,IE6 與 IE7 都不支持這個屬性,直到 IE8 才開始支持。
在老 IE 中,需要通過 document.frames 集合訪問:
document.frames['myframe'].document;
推薦使用 contentWindow 屬性。它是個只讀屬性,返回指定 iframe 的窗口對象。雖然它並不是標準的一部分,但主流瀏覽器都支持,因此成了事實上的兼容方案:
document.getElementById('myframe').contentWindow.document
把三種情況收攏到一起,調用時就不用再操心環境差異:
function getIframeDoc(id) {
var frame = document.getElementById(id);
if (!frame) return null;
// 標準瀏覽器與 IE8+
if (frame.contentDocument) {
return frame.contentDocument;
}
// IE6 / IE7
if (frame.contentWindow && frame.contentWindow.document) {
return frame.contentWindow.document;
}
// 更老的 IE
return document.frames[id] ? document.frames[id].document : null;
}
contentDocument 都會失敗。跨域交互需要雙方通過 postMessage 通信,或由服務端配置合適的 CORS 響應頭。null 或不完整的 DOM。應該監聽 iframe 的 load 事件,或在輪詢中判斷對象是否就緒。document.createElement('iframe') 創建並插入文檔後,某些瀏覽器需要額外寫入 document.open()/write()/close() 才能拿到穩定的文檔對象,實測差異較大,建議盡量用 src 指向真實頁面。