DIV CSS 佈局教程網

JavaScript 操作 iframe 的方法整理與跨瀏覽器差異
編輯:關於JavaScript     

iframe 的操作始終繞不開兩件事:跨瀏覽器的屬性名稱差異,以及同源政策的限制。以下逐一整理。凡是跨網域的存取,都會被同源政策阻擋。

1. 取得 iframe 的 window 物件

各瀏覽器在這點上難得一致:

chrome:  iframeElement.contentWindow
firefox: iframeElement.contentWindow
ie6:     iframeElement.contentWindow

曾有文章提到「iframe 元素物件有 contentDocument 屬性,可透過它的 parentWindow 取得 window 物件」,但實測 Firefox 與 Chrome 的 element.contentDocument 並沒有 parentWindow 屬性(那是 IE 的寫法)。因此:

function getIframeWindow(element) {
    return element.contentWindow;
    // return element.contentWindow || element.contentDocument.parentWindow;
}

2. 取得 iframe 的 document 物件

這裡才有真正的分歧:

chrome:  iframeElement.contentDocument
firefox: iframeElement.contentDocument
ie:      element.contentWindow.document   (IE 沒有 contentDocument 屬性)

相容寫法:

var getIframeDocument = function (element) {
    return element.contentDocument || element.contentWindow.document;
};

3. 在 iframe 中取得父頁面的 window 物件

window.parent   // 父頁面
window.top      // 頂層頁面

這兩個屬性適用於所有瀏覽器。若頁面沒有被巢入任何框架,window.parent === window.top === window。

4. 取得 iframe 在父頁面中的 HTML 標籤元素

window.frameElement   // 型別為 HTMLElement,適用於所有瀏覽器

5. iframe 的 onload 事件

非 IE 瀏覽器都提供了 onload。以下程式碼在 IE 中不會跳出提示框:

var ifr = document.createElement('iframe');
ifr.src = 'https://www.jb51.net/index.php';
ifr.onload = function () {
    alert('loaded');
};
document.body.appendChild(ifr);

但 IE 其實也「有」onload,只是綁定方式不同。以下兩種寫法在 IE 中都會觸發:

方法一:直接寫在標籤上

<iframe onload="alert('loaded');" src="https://www.jb51.net/index.php"></iframe>

方法二:用 createElement 傳入完整 HTML(僅 IE 支援這種用法)

// 只有 IE 才支援為 createElement 傳遞這樣的參數
var ifr = document.createElement('<iframe onload="alert(\'loaded\');" src="https://www.jb51.net/index.php"></iframe>');
document.body.appendChild(ifr);

由於 iframe 元素是包含於父級頁面之中,上述方法都不涉及跨域問題。

歸根究底,IE 確實提供了 onload 事件,但必須用 attachEvent 綁定:

var ifr = document.createElement('iframe');
ifr.src = 'https://b.jb51.net/b.php';
if (ifr.attachEvent) {
    ifr.attachEvent('onload', function () { alert('loaded'); });
} else {
    ifr.onload = function () { alert('loaded'); };
}
document.body.appendChild(ifr);

6. window.frames

window.frames 可以取得頁面中所有的框架(iframe、frame 等)。要注意的是取到的是 window 物件,而不是 HTMLElement:

var ifr1 = document.getElementById('ifr1');
var ifr1win = window.frames[0];
ifr1win.frameElement === ifr1;   // true
ifr1win === ifr1;                // false

這兩行的對比很能說明問題:frames[0] 給你的是 iframe 內部的 window,而 getElementById 給你的是 iframe 這個標籤;兩者透過 frameElement 互相指向對方。

今日的標準寫法

上面這些相容分支在今天可以大幅簡化,因為 IE 已不在支援範圍內:

// window 物件
var win = iframe.contentWindow;

// document 物件
var doc = iframe.contentDocument;      // 所有現代瀏覽器皆支援

// onload,用標準事件綁定
iframe.addEventListener("load", function () {
    console.log("iframe 已載入");
});

跨網域時,contentDocument 會回傳 null,此時唯一被允許的溝通方式是 postMessage:

// 父頁面 → iframe
iframe.contentWindow.postMessage({ type: "resize", height: 500 }, "https://child.example.com");

// iframe 內部 → 父頁面
window.addEventListener("message", function (e) {
    if (e.origin !== "https://parent.example.com") return;   // 務必驗證來源
    // 處理 e.data
});
window.parent.postMessage({ type: "ready" }, "https://parent.example.com");

使用 postMessage 時有兩個必須遵守的原則:訊息接收方一定要檢查 event.origin,發送時也應明確指定目標 origin 而非使用 "*",否則等於把資料廣播給任何嵌入你的頁面。

另外提醒一個現代場景的相關屬性:iframe.allow="fullscreen"、loading="lazy"、sandbox="allow-scripts allow-same-origin"。其中 sandbox 是限制第三方 iframe 權限最有力的工具,預設會禁掉腳本、表單與彈出視窗,需要什麼才逐一開放。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved