简体   繁体   中英

Dynamically Adding HTML into an iFrame - Javascript

I'm attempting to dynamically create an iFrame and add HTML into it from the current document. The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it.

Here's my code:

function createiFrame(min, max, key) {
    console.log("Max-Width", max);

    //CREATING A CLASS FOR THE IFRAME
    var iframeClass = key + "-" + max;
    //var path = window.location.pathname;
    //var page = path.split("/").pop();

    //ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
    $(document).ready(function() {
        $('<iframe>', {
            width: max
        }).addClass(iframeClass).prependTo('body');
    });


    var requiredHTML = document.getElementById('container').innerHTML;
    console.log("RequiredHTML", requiredHTML);

    //ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE 
    //IT STOPS WORKING
    $('.' + iframeClass).ready(function() {
        console.log("iFrame ready");
        $('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
    });

    var $head = document.getElementsByTagName('head')[0].innerHTML;
    $(document).ready(function() {
        $('.' + iframeClass).contents().find('head').append($head);
    });


}

EDIT

I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet.

So new question;

How do I get the DOM ready?

check out this post: addEventListener to iFrame

you need to use $('#myIFrame').load(function(){ ....

$('.' + iframeClass).ready(function() {
    ...
}

Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. This should work based on that.

$(iframeClass document).ready(function() {
    ...
}

I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM