从chrome扩展程序访问/编辑iframe的内容



我想通过chrome扩展名编辑iframe的内容,但无法这样做,因为iframe的contentWindow/contentDocument返回未定义。一直在四处寻找答案,据我了解,如果 iframe 从一开始就存在于页面上,则很容易修复,但事实并非如此。有问题的iframe是gmail撰写文本区域,它采用iframe的形式,它是动态添加到DOM中的。有没有办法通过 chrome 扩展程序做到这一点?

编辑:对不起。Rob W 让我意识到内容确实可以访问文档。我在这里尝试做的是在Gmail中添加一些额外的功能,在工具栏中有一个按钮,可以在撰写窗口中添加一些html。我现在的按钮部分工作,它添加了 html,但它没有像它应该的那样在插入符号处执行此操作,因为我无法访问 contentWindow 来执行此操作:

range = iWindow.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);

有什么解决方案吗?

contentWindow

Chrome扩展程序中无法访问。
另一方面,contentDocument 正确返回框架内的文档,前提是 iframe 位于同一来源,Gmail 就是这种情况。

下面是一个 Gmail 示例。为简单起见,我假设文档中只有一个编辑器。

var poller = setInterval(function() {
    var editor = document.querySelector('iframe.editable');
    if (editor && editor.contentDocument && !editor.__rwHandled) {
        editor.__rwHandled = true; // Run once for an editor instance
        var textNode = document.createTextNode('It works!');
        editor.contentDocument.body.appendChild(textNode);
    }
}, 200);

每当您想停止轮询器时,只需使用 clearInterval(poller); .确保检测方法便宜。例如:查询 DOM 节点是可以的,打开新窗口不是。

最新更新