2013-07-18 64 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

相关问题