Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set iframe innerHTML without loading page in it (with jquery)

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.

like image 221
Leto Avatar asked Nov 22 '11 11:11

Leto


Video Answer


2 Answers

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();
like image 142
newtover Avatar answered Oct 13 '22 00:10

newtover


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)
like image 36
Jonathan Schneider Avatar answered Oct 13 '22 00:10

Jonathan Schneider