Alvaro Alvaro - 5 months ago 20
Javascript Question

Append a whole page to an iframe

I would like to append a whole page (with

<html><head>
and
<body>
elements) inside an existent empty iframe.

Is it possible at all?

As far as I've seen they always append the content to some child element in the iframe, such as
body
:

$('#demo').contents().find('body').html('aaa');


But I'm trying the append a whole page, with styles, head and so on, so I would need to append it to the document level.
Something like this:

//not working
$('#demo').contents().html('<html><body>aaaa</body></html>');

Answer

You could use document write() method, like this:

var iframeDoc = $('iframe')[0].contentDocument; // jQuery is just for the example of course
iframeDoc.write(data);

Where data is a full valid page source string, including DOCTYPE, HEAD, etc...

-DEMO-

Comments