【问题标题】:Accessing/editing the content of an iframe from a chrome extension从 chrome 扩展访问/编辑 iframe 的内容
【发布时间】:2012-12-02 13:22:40
【问题描述】:

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

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

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

有什么解决办法吗?

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    contentWindow is not accessible in Chrome extensions
    另一方面,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 节点可以,打开新窗口不行。

    【讨论】:

    • 感谢您的回答。我对我的问题进行了编辑。对不起,我确定这是因为我对此经验不足,但我无法真正理解您的答案。我确实尝试了很多,我确实尝试使用 executeScript 在 iframe 中添加内容脚本,但我真的无法让它工作。抱歉,非常感谢您迄今为止的帮助。
    • @Clox 那是因为您的代码确实需要访问窗口对象,才能使用window.getSelection();Inject a script 做你想做的事。如果您想在页面和内容脚本之间进行通信,请设置自定义事件或use postMessage
    • Gmail 中的 iframe 似乎并不总是从同一来源加载;如果您将鼠标悬停在主电子邮件列表视图中的发件人上,您会得到一个小框(他们显然称之为悬停卡)。此框由从以下位置加载的 iframe 创建:apis.google.com/u/0/_/streamwidgets/…... - 您可以使用“all_frames”影响这些 iframe:true stackoverflow.com/questions/6641729/…
    猜你喜欢
    • 2011-04-25
    • 2012-07-04
    • 2012-10-27
    • 2013-05-20
    • 1970-01-01
    • 2017-05-04
    • 2012-08-20
    相关资源
    最近更新 更多