0

I'm trying to append html inside the <head> tag of an iframe I'm creating, but instead of appending to my iframe's head, my code is being appended to the head of the actual page I'm on. I have no idea why that's happening!

Here's what I've tried:

    $('body').append('<iframe src="/test-iframe.html" id="if"></iframe>');
    $('#if').ready(function(){
        $('head', window.frames['if'].document).append('<scr'+'ipt src=/script.js></scr'+'ipt>');
    });

And I also tried this:

    $('body').append('<iframe src="/test-iframe.html" id="if"></iframe>');
    $('#if').ready(function(){
        $('#if').contents().find('head').append('<scr'+'ipt src=/script.js></scr'+'ipt>');
    });

But in both cases the result ends up looking something like:

<html>
    <head>
        <script src="/script.js"></script>
    </head>
    <body>
        <iframe src="/iframe-test.html">
            <html><head></head><body>test page</body></html> <!-- This is the source of the iFrame after it loaded, obviously -->
        </iframe>
    </body>
</html>

As you can probably see it has indeed appended my script tag to the wrong <head> tag.

How can I make it so it DOES append to the <head> tag inside of my iFrame?

Metoniem
  • 239
  • 2
  • 15
  • 2
    See http://stackoverflow.com/questions/9530455/appending-content-into-a-dymanically-created-iframe-gets-an-empty-iframe – Deckerz Apr 11 '17 at 11:05
  • @Deckerz Thanks! That works. Now I have a completely different issue, though :-( I'll have to make a new question about that. – Metoniem Apr 11 '17 at 11:15
  • why are you concatenating your string like `''` out of curiosity :) – madalinivascu Apr 11 '17 at 11:21
  • @madalinivascu That jQuery code sits directly in a `` somewhere in the middle, it'll close your script tag and everything behind it will be considered plaintext! – Metoniem Apr 11 '17 at 12:07
  • @madalinivascu Here's more info about that: http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write?rq=1 – Metoniem Apr 11 '17 at 12:08

0 Answers0