2013-07-18 63 views
1

我正在寫一個在網頁中打開iframe的firefox插件。我想在iframe中選擇的對象,但我不能訪問內容:訪問iframe內容(在Firefox插件中的javascript)

var iframe = content.document.getElementById("MyBeautifulIframe"); 
if (iframe) 
{ 
    var mydiv = iframe.contentDocument.getElementById("mydiv"); 
} 

Erreur : TypeError: iframe.contentDocument is undefined

我iframe.content.document.getElemen ...,iframe.document.getElemen ...同樣tryed結果。

如何訪問iframe dom?如果我查看iframe var類型,它是[object XrayWrapper [object XULElement]],如何訪問XULElement對象的dom對象?

回答

1

更新答案:

接過一看你的代碼,我想我可能已經找到了你的問題。

你正在做的:

var iframe = content.document.getElementById("muzich_iframe_addcontainer"); 
if (iframe) 
{ 
    if (iframe.contentDocument.getElementById("div")) 
    { 
    this.close_all(); 
    } 
} 

muzich_iframe_addcontainer是一個div,而不是iframe的,所以它永遠不會有contentDocument。 此外,我無法通過創建xul元素使其工作。我必須創建html div和iframe才能使其工作。

下面的代碼:

var htmlns = "http://www.w3.org/1999/xhtml"; 
var container = document.createElementNS(htmlns,'div'); 
container.setAttribute("id", "muzich_iframe_addcontainer"); 
container.setAttribute("style", styleContainer); //styleContainer is the one you use without the background stuff 
window.content.document.body.appendChild(container); 

var iframe = document.createElementNS(htmlns,'iframe'); 
iframe.setAttribute("id", "muzich_iframe"); 
iframe.setAttribute("style", 
    "width: 100%; height: 100%; " 
); 

iframe.setAttribute("src", "http://www.lifehacker.com"); // Used it as my example url 
window.content.document.getElementById("muzich_iframe_addcontainer").appendChild(iframe); 

然後,當您要檢查收你做:

var iframe = window.content.document.getElementById("muzich_iframe"); 
if (iframe) 
{ 
    if (iframe.contentDocument.getElementById("div")) 
    { 
    this.close_all(); 
    } 
} 

希望這一個解決它。

+0

I'vce嘗試完全加載iframe後執行此代碼,結果相同。 – bux

+0

你能發佈創建和加載你的iframe的代碼來試圖找出問題嗎? –

+0

代碼:https://github.com/buxx/MuzichXpi/blob/master/chrome/content/muzichXpi.js#L113(在這個版本中'start_listener'沒有被調用)。 Iframe創建l。 – bux

相關問題