// 所有主流瀏覽器 (含 IE6+) 均支援
var iframeWin = iframeElement.contentWindow;
注意:受同源策略限制,跨域 iframe 無法存取其 window 物件屬性/方法。
var iframeDoc = iframeElement.contentDocument || iframeElement.contentWindow.document;
// contentDocument: Firefox, Chrome, IE8+
// contentWindow.document: IE6/7
// 父頁面
var parentWin = window.parent;
// 頂層頁面 (跨多層 iframe)
var topWin = window.top;
// 同源策略同樣適用
// iframe 內部執行
var myIframeElement = window.frameElement; // 回傳父頁面中的 <iframe> 元素 (HTMLElement)
// 所有瀏覽器支援,不受同源策略限制 (僅能取得元素參考,無法操作父頁面 DOM 若跨域)
非 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);
<iframe onload="alert('loaded')" src="...></iframe>
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 標頭 |
try...catch 捕獲跨域拋出的錯誤。iframe.src = 'about:blank' → iframe.parentNode.removeChild(iframe) → iframe = null,防止記憶體洩漏 (特別是 IE)。sandbox 屬性最小化權限:sandbox="allow-scripts allow-same-origin allow-forms"。