从chrome扩展中访问/编辑iframe的内容 [英] Accessing/editing the content of an iframe from a chrome extension

查看:706
本文介绍了从chrome扩展中访问/编辑iframe的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过chrome扩展来编辑iframe的内容,但无法执行,因为iframe的contentWindow / contentDocument返回未定义。
一直在四处寻找答案,正如我已经理解的那样,如果iframe从一开始就在页面上存在,它很容易修复,但它不会。
所讨论的iframe是以iframe形式的gmail撰写文本区域,并且它被动态添加到DOM。
有没有办法通过chrome扩展来做到这一点?

I'd like to edit the content of an iframe through a chrome extension but am unable to because contentWindow/contentDocument of the iframe returns undefined. Been looking around for an answer and as I've understood it it's easily fixed if the iframe exists on the page from the beginning, but it doesn't. The iframe in question is the gmail compose text area which is in the form of an iframe, and it's added to the DOM dynamically. Is there any way to do this through a chrome extension?

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

I'm sorry. Rob W Made me realize the contentDocument indeed can be accessed. What I'm trying to do here is add some extra functionality in Gmail, having a button in the toolbar that adds some html in the compose window. I now have the button partially working, it adds the html but It doesn't do it at the caret like its supposed to since I can't access contentWindow in order to do this:

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

任何解决方案?

Any solution to this?

推荐答案

contentWindow 在Chrome扩展程序中无法访问。另一方面,
contentDocument 可正确返回文档一个框架,前提是iframe与原来的位置相同,Gmail就是这种情况。

contentWindow is not accessible in Chrome extensions.
contentDocument, on the other hand, correctly returns the document within a frame, provided that the iframe is at the same origin, which is the case for Gmail.

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

Here's an example for Gmail. For simplicity, I assumed that there's only one editor in the document.

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节点是好的,打开新窗口不是。

Whenever you want to stop the poller, just use clearInterval(poller);. Make sure that the methods you for detection are inexpensive. Eg: querying for a DOM node is OK, opening new windows isn't.

这篇关于从chrome扩展中访问/编辑iframe的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆