Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add dynamical elements in a Iframe element than i create

i have a litle problem if i create a dynamically IFRAME element and i agregate dynamically elements to the new iframe. It works If i do that:

var miiframe=document.getElementById("miiframe");
var myElement=content.document.createElement("LABEL");
myElement.innerHTML="blabla";
miiframe.contentDocument.body.appendChild(myElement);

but if i do that doesn't works:

var miiframe=content.document.createElement("IFRAME");
miiframe.src="about:blank";
document.body.appendChild(miiframe);
var myElement=content.document.createElement("LABEL");
myElement.innerHTML="blabla";
miiframe.contentDocument.body.appendChild(myElement);

i see the iframe but i don't see the label element. The most courious is if before appendElement i do and alert it works!!!

var miiframe=content.document.createElement("IFRAME");
miiframe.src="about:blank";
document.body.appendChild(miiframe);
var myElement=content.document.createElement("LABEL");
myElement.innerHTML="blabla";
alert("now works!!!");
miiframe.contentDocument.body.appendChild(myElement);

With DIV element works but i want do that with IFRAME element!!!

This code is for Firefox. Thanks!!

like image 299
user322172 Avatar asked Dec 17 '22 01:12

user322172


2 Answers

If you put a "src" to your iframe, it tries to load this source (even if it is a "about:blank"). After the loading is done, it overwrites your label. You can add a listener to wait for the iframe loading:

var miiframe=content.document.createElement("IFRAME");
miiframe.src="about:blank";
miiframe.addEventListener('load', function (e) {
    var myElement=content.document.createElement("LABEL");
    myElement.innerHTML="blabla";
    miiframe.contentDocument.body.appendChild(myElement);
}, false);

document.body.appendChild(miiframe);
like image 104
Reto Aebersold Avatar answered Jan 16 '23 19:01

Reto Aebersold


My case was a bit different, I didnt specify any source I was just trying to create an HTML editor, I was making something like this:

function init() {
    var iframe = document.createElement("iframe");
    iframe.setAttributes('id','edit');
    document.body.appendChild(iframe);
    var y = document.getElementById('edit');
    y.contentDocument.designMode = 'On';
}

But that never worked, the curious thing is that when I put some alerts inside some ifs for example if('designMode' in y) and stuff like that, after a couple of alerts I was able to write on the iframe.... :S

Thank you very much for your help, your explanation is clear, the iframe always try to load.... it overwrites any other instruction before... so I changed it and now is working a 100% :)

function init() {
    var iframe = document.createElement("iframe");
    iframe.addEventListener('load', function () {
    iframe.contentDocument.designMode="on";
    }, false);
    document.body.appendChild(iframe);
}
like image 24
Jairo Avatar answered Jan 16 '23 19:01

Jairo