萬盛學電腦網

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

JavaScript 操作 iframe 完全指南:取得 window/document、跨域限制、onload 事件相容

1. 取得 iframe 的 window 物件

// 所有主流瀏覽器 (含 IE6+) 均支援
var iframeWin = iframeElement.contentWindow;

注意:受同源策略限制,跨域 iframe 無法存取其 window 物件屬性/方法。

2. 取得 iframe 的 document 物件

var iframeDoc = iframeElement.contentDocument || iframeElement.contentWindow.document;
// contentDocument: Firefox, Chrome, IE8+
// contentWindow.document: IE6/7

3. iframe 內取得父頁面 window

// 父頁面
var parentWin = window.parent;
// 頂層頁面 (跨多層 iframe)
var topWin = window.top;
// 同源策略同樣適用

4. 取得 iframe 在父頁面中的 DOM 元素

// iframe 內部執行
var myIframeElement = window.frameElement; // 回傳父頁面中的 <iframe> 元素 (HTMLElement)
// 所有瀏覽器支援,不受同源策略限制 (僅能取得元素參考,無法操作父頁面 DOM 若跨域)

5. iframe onload 事件跨瀏覽器綁定

問題

非 IE 瀏覽器支援 iframe.onload,IE 需使用 attachEvent。

統一綁定函式

function bindIframeLoad(iframe, callback) {
    if (iframe.attachEvent) { // IE
        iframe.attachEvent('onload', callback);
    } else {
        iframe.onload = callback;
    }
}

// 使用範例
var ifr = document.createElement('iframe');
ifr.src = 'https://example.com/page.html';
bindIframeLoad(ifr, function() {
    console.log('iframe 載入完成');
    // 同源情況下可操作 iframe 內容
});
document.body.appendChild(ifr);

HTML 內聯寫法 (IE 也支援)

<iframe onload="alert('loaded')" src="...></iframe>

6. window.frames 集合

var ifr1 = document.getElementById('ifr1');
var ifr1Win = window.frames[0]; // 或 window.frames['iframeName']
console.log(ifr1Win.frameElement === ifr1); // true
console.log(ifr1Win === ifr1);              // false (window vs HTMLElement)

window.frames 回傳的是 Window 物件,非 DOM 元素。

跨域解決方案速查

場景方案
同主域不同子域設定 document.domain = 'example.com' (雙方皆需設定,僅限同主域)
完全不同域postMessage API (HTML5 標準,雙向通訊)
舊瀏覽器跨域window.name 跨域、location.hash 傳遞、document.domain + proxy 頁面
嵌入第三方內容sandbox 屬性限制權限、CSP 標頭

最佳實踐清單

  • 永遠檢查同源後再操作 iframe 內容,使用 try...catch 捕獲跨域拋出的錯誤。
  • 動態建立 iframe 時,先綁定 onload 再設定 src,避免競態條件。
  • 銷毀 iframe 時:iframe.src = 'about:blank' → iframe.parentNode.removeChild(iframe) → iframe = null,防止記憶體洩漏 (特別是 IE)。
  • 使用 sandbox 屬性最小化權限:sandbox="allow-scripts allow-same-origin allow-forms"。
copyright © 萬盛學電腦網 all rights reserved