2

I'm trying to add some html elements inside a iframe, to personalize a site. I'm building a browser extension, so there is no cross-domain problem. I have the iframe:

<iframe id="container" src="http://www.google.com">
    <p>Your browser does not support iframes.</p>
</iframe>

and then, when the document is already loaded, I create the element and insert it... But it is never shown in the iframe. But I am allowed to get an iframe-existent element and to change it's properties. So, I have access to the elements but not for create new ones? Why?

var ifr = document.querySelector("#container");
var ifrDoc = ifr.contentWindow || ifr.contentDocument;
    if (ifrDoc.document) ifrDoc = ifrDoc.document;

var elem = ifrDoc.createElement("div");
    elem.innerHTML = "Demo Box";
    elem.style.width = "50px";
    elem.style.height = "50px";
    elem.style.position = "absolute";
    elem.style.background = "red";

ifrDoc.body.appendChild(elem);

Here a JSFiddle demo to understand the problem (remember extensions have another privileges): http://jsfiddle.net/TH48e/40/

Any idea?

erikvold
  • 15,988
  • 11
  • 54
  • 98
gal007
  • 6,911
  • 8
  • 47
  • 70

1 Answers1

5

After your clarification in comments:

var ifr = gBrowser.selectedBrowser.contentDocument.getElementById('container')

Dont do that .contentWindow then get the document from that, its useless redundant etc.

Also dont do querySelector if you want to just get something by id anyways, huge speed difference, getElementById is much faster.

Also don't do .innerHTML the addon approvers won't accept it because it leads to security issues. Do .textContent.

Your fiddle will not work because:

  1. You can't do cross frame communication
  2. I'm not sure but I think: createElement is a "native" function in javascript so reserved in away although it is document.createElement but ya

This fiddle works, the rawr function is undefined in body, I'm not sure why so i moved the script to the document:

http://jsfiddle.net/TH48e/43/

<script>
function createElementMY(){
    var doc = document.getElementById('container');

    var ifrDoc = doc.contentDocument;


    var elem = ifrDoc.createElement("div");
    elem.textContent = 'Test';
    ifrDoc.body.appendChild(elem);
}
</script>
<iframe id="container" src="data:text/html,rawr"></iframe>
<button onclick="createElementMY()">Click me!</button>
Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • Hey! Thanks you a lot for all the explanation! But I still have the problem. In your demo you are using an "empty" iframe, not linked to any external url. I updated the demo (http://jsfiddle.net/TH48e/45/) to work with external sources and it throws the erro: Permission denied to access property 'document' – gal007 Nov 26 '14 at 14:37
  • 2
    In content code you will get that error. But from privelaged scope (chrome scope) you won't get that error. See: http://stackoverflow.com/questions/3083112/jquery-cross-domain-iframe-scripting – Noitidart Nov 26 '14 at 16:17