12

I want to set the contents of an iframe dynamically, when no pages were loaded before in the iframe.

I'm doing that :

iframe = $('<iframe id="thepage"></iframe>');

iframeHtml = 'iframeHtml';
$('body').append(iframe);

iframe
.contents()
.html(iframeHtml);

But it is not working, the html is still empty.

2
  • what is your console telling you? Commented Nov 22, 2011 at 11:53
  • nothing, it seems to work :) ([Document about:blank] from firebug) Commented Nov 22, 2011 at 11:57

5 Answers 5

26

the best way to populate frame contents is document.write

var dstFrame = document.getElementById('yourFrameId');
var dstDoc = dstFrame.contentDocument || dstFrame.contentWindow.document;
dstDoc.write(yourHTML);
dstDoc.close()

UPD: that is

var iFrame = $('<iframe id="thepage"></iframe>');
$('body').append(iFrame);

var iFrameDoc = iFrame[0].contentDocument || iFrame[0].contentWindow.document;
iFrameDoc.write('<p>Some useful html</p>');
iFrameDoc.close();
Sign up to request clarification or add additional context in comments.

Comments

12

If you want to avoid using document.write, which is generally not recommended any longer, you can get at the frame contents to add the content:

iframe = $('<iframe id="thepage"></iframe>')
iframeHtml = 'iframeHtml'
$('body').append(iframe)
iframe.contents().find('body').html(iframeHtml)

Comments

9

Using JQuery, you can edit the iframe's attribute srcdoc by passing it the html as string:

$('#iframe_id').attr("srcdoc", htmlString);

1 Comment

This is pretty good, though it wouldn't load any script tags inside.
3
iframe = $('<iframe id="thepage"></iframe>');

iframeHtml = 'iframeHtml'; $('body').append(iframe);

iframe .contents() .html(iframeHtml);

the reason it does not work is because contents() returns a document object and html() only works on HTMLElemnt objects, html() is basically a wrapper around innerHTML property and document does not have such property.

Comments

0

Use the jQuery contents() method.

You can use the jQuery contents() method in combination with the find(), val() and html() methods to insert text or HTML inside an iframe body.

var EditFrame = $("#EditWindow").contents().find('body');  
var message = "Your message which needs to show in Iframe";
EditFrame.html(message);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.