Clox
Clox

Reputation: 1943

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

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?

Upvotes: 2

Views: 2205

Answers (1)

Rob W
Rob W

Reputation: 349192

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.

Upvotes: 3

Related Questions