Add dynamical elements in a Iframe element than i create

12,082

Solution 1

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

Solution 2

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);
}
Share:
12,082
Admin
Author by

Admin

Updated on June 30, 2022

Comments

  • Admin
    Admin almost 2 years

    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!!