Accessing/editing the content of an iframe from a chrome extension

不羁的心 提交于 2019-12-21 22:26:49

问题


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?

Edit: 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?


回答1:


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.

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);

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.



来源:https://stackoverflow.com/questions/13669671/accessing-editing-the-content-of-an-iframe-from-a-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!