60

I am trying to insert some content into a 'blank' iFrame, however nothing is being inserted.

HTML:

<iframe id="iframe"></iframe>

JS:

$("#iframe").ready(function() {
    var $doc = $("#iframe").contentWindow.document;
    var $body = $("<body>").text("Test");
    $body.insertAfter($doc);
});

I am calling the ready function so I don't understand why it is not inserting.

user2521439
  • 1,405
  • 2
  • 13
  • 19

5 Answers5

125

You really don't need jQuery for that:

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();

jsFiddle Demo

If you absolutely have to use jQuery, you should use contents():

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append('Test');
});

jsFiddle Demo

Please don't forget that if you're using jQuery, you'll need to hook into the DOMReady function as follows:

$(function() {  
    var $iframe = $('#iframe');
    $iframe.ready(function() {
        $iframe.contents().find("body").append('Test');
    });
});
BenM
  • 52,573
  • 26
  • 113
  • 168
  • 1
    I agree that jQuery is a bit overkill for some simple DOM manipulation but I've already got it for other parts of the page anyway, but thanks for the detailed response – user2521439 Feb 15 '14 at 09:48
  • 1
    No problem, glad to help. Please bear in mind though that using jQuery is not always best option. In this example, it will be slower, of course. – BenM Feb 15 '14 at 09:48
  • 3
    Anyone faced any cross-domain security validations thrown by IE ? I am seeing those with this example. Any idea on how to work arounds ? – AlexVPerl Mar 25 '15 at 23:18
  • Changed to `var ifr = d.getElementById('iframe'), doc = ifr.contentDocument || ifr.contentWindow.document;`. Got it from http://thinkofdev.com/javascript-how-to-load-dynamic-contents-html-string-json-to-iframe –  Aug 15 '19 at 15:07
  • 1
    This is not a bad solution because many browsers give you a warning when you use doc.write(); it is highly discouraged. – Dennis Kozevnikoff Jul 30 '21 at 14:56
4

This should do what you want:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test');
Pavel Štěrba
  • 2,822
  • 2
  • 28
  • 50
  • 3
    Just because he's named variables with `$` doesn't mean it's a weird combination of PHP and JS. I actually sometimes name variables that hold jQuery objects as `$testDiv`, for example. It helps me track jQuery objects inside my code... The prepended `$` on variable names has nothing to do with JS syntax... – BenM Feb 15 '14 at 09:43
  • 1
    Ok sorry, offensive tone removed. – Pavel Štěrba Feb 15 '14 at 09:44
  • @PavelŠtěrba None taken :) – user2521439 Feb 15 '14 at 09:44
  • 1
    If you're using the jquery function `find` does that mean the iframe already has a body tag in it - or am I missing somehting? – user2521439 Feb 15 '14 at 09:46
  • 4
    @user2521439 yes. iframes are created with a blank document inside. The browser will automatically add `` to your iframe's contentDocument. – BenM Feb 15 '14 at 09:47
4

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

andilabs
  • 22,159
  • 14
  • 114
  • 151
3

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

  • 1
    It would be better to have text in English (even though in this case understanding it is not very important). Also, as a general tip, a few words to explain how your solution works would be welcome. It would save people from analysing the code to understand whether your solution is what they are looking for. Thank you! – Fabio says Reinstate Monica Aug 30 '16 at 15:18
2

If you want all the CSS thats on your webpage in your IFrame, try this:

var headClone, iFrameHead;

// Create a clone of the web-page head
headClone = $('head').clone();

// Find the head of the the iFrame we are looking for
iFrameHead = $('#iframe').contents().find('head');

// Replace 'iFrameHead with your Web page 'head'
iFrameHead.replaceWith(headClone);

// You should now have all the Web page CSS in the Iframe

Good Luck.

Aakash
  • 21,375
  • 7
  • 100
  • 81