从Firefox扩展访问iFrame的DOM

3

我已经花了很长时间尝试不同的方法让这个工作,但是什么都不起作用,文档也没有多大帮助。

我正在尝试填充一个在 iframe 中的表单,而这个 iframe 是我动态注入到页面中的。我注入 iframe 的代码如下:

myObject.iframe = document.createElement("iframe");
myObject.iframe.setAttribute("src", data.url);
myObject.iframe.setAttribute("id","extension-iframe");
myObject.window.document.getElementById('publisher').appendChild(myObject.iframe);
myObject.iframe.addEventListener("load", function(){
    myObject.populate(data);
}, false);

这段代码运行良好,并且确实触发了populate()方法。我的问题在于如何获取iframe的document或window对象。我尝试了以下所有方法:

myObject.iframe.window
myObject.iframe.document
myObject.iframe.content

但是这些都没有定义。
我还尝试将事件对象传递给该iframe的加载事件监听器,然后执行:
event.originalTarget

但那也没起作用。
我正在阅读以下文档:

但我要么没有理解它,要么它没有被恰当地解释。

有人能够解释一下吗?

谢谢!

4个回答

3

您尝试过使用contentWindow属性吗?

var doc = iframe.contentWindow.document;

我已经尝试了,但仍然无法访问该窗口。请查看以下链接以获取更完整的解释:http://gist.github.com/242927提前感谢您的所有帮助。 - luisgo
抱歉,我对XUL不熟悉,没有其他的建议了。 - Sam C
contentWindow在XUL加载时不可用。具有讽刺意味的是,如果您使用JS调试器,则它可以正常工作,因为您会在更晚的时间步进。 - NoBugs

1

我传递了事件对象,然后使用event.originalTarget(就像你提到的那样),它运行良好。虽然我不得不将addEventListener的useCapture参数设置为true,以便调用我的事件。

所以如果我理解正确,您需要在populate方法中访问文档...

我会将event.originalTarget作为参数传递给您的方法, 或者 在加载事件中,例如我会设置myObject.document属性,然后在populate方法中使用它。

myObject.iframe.addEventListener("load", function(event){
    var doc = event.originalTarget;
    myObject.populate(data,doc);
}, false);

1

尝试使用myObject.iframe.contentDocument

类似于这样的东西:

// For accessing browser window from sidebar code.
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   .rootTreeItem
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIDOMWindow);

var gBrowser = mainWindow.gBrowser;

var iframes = gBrowser.contentDocument.getElementsByTagName("iframe");
            for (var i=0; i < iframes.length; i++) {
                var check_elem = iframes[i].contentDocument.getElementById('myid');
                if (check_elem) {
                    ...;
                }
            }

这可能适用于浏览器,但对于XUL iframes呢?我可以确认Lukasz Salamon的答案适用于XUL。 - NoBugs

0

我几乎遇到了同样的问题。使用以下代码可以获取iframe(调试时使用Firebug):

iframes = window.content.document.getElementsByTagName('iframe')
for (var i = 0; i < iframes.length; i++) {
  var elmInput = iframes[i];
  Firebug.Console.log(elmInput);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接